主要成分:绑定事件发生多次 [英] Backbone: bind event happen multiple times

查看:148
本文介绍了主要成分:绑定事件发生多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做一个简单的待办事项应用:

I make a simple todo app:

var Todo = Backbone.Model.extend({

});

var Todos = Backbone.Collection.extend({
    model: Todo
});

var todos = new Todos();

var ItemView = Backbone.View.extend({
    tagName: "li",
    template: _.template($("#item-template").html()),
    render: function () {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    },
    initialize: function () {
        this.listenTo(todos, 'remove', this.remove);
    },
    events: {
        "click .delete": "clear"
    },
    clear: function () {
        todos.remove(this.model);
    }
});

var AppView = Backbone.View.extend({
    el: $("body"),
    initialize: function () {
        this.listenTo(todos, 'add', this.addOne);
    },  
    addOne: function(todo) {
        var view = new ItemView({
            model: todo
        });
        this.$("#list").append(view.render().el);
    },    
    events: {
        "click #create": "create"
    },
    create: function () {
        var model = new Todo({
            title: this.$("#input").val()
        });
        todos.add(model);
    }
})

var app = new AppView();

和在线演示是在这里: http://jsfiddle.net/JPL94/1/

and DEMO online is here: http://jsfiddle.net/JPL94/1/

我可以正确添加项目,但是当我想删除一些项目,他们都被删除;

I can add item correctly, but when I want delete some item, all of them been removed;

我发现当我点击它涉及到绑定事件 ItemView控件,一是删除按钮,所有的人被触发。

I found it related to the bind event in ItemView, when I click one delete button, all of them are triggered.

但我怎么能解决这个问题?

But how can I solve this problem?

推荐答案

您现在收听的是集合中移除活动,如果我没记错的集合将派遣每当模型被删除的删除事件,所以当你从集合中删除一个模型中,所有的意见,会看到该事件。

You are listening to remove events from the collection, and if my memory serves me right a collection will dispatch a remove event whenever a model is removed, so when you remove a model from the collection, all the views will see the event.

我改变了你的初始化视图以

I changed your initialize in the view to

initialize: function () {
    this.listenTo(this.model, 'remove', this.remove);
},

和它似乎工作。

http://jsfiddle.net/JPL94/5/

这篇关于主要成分:绑定事件发生多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆