Backbone.js集合方法绑定

时间:2011-10-13 21:10:24

标签: javascript backbone.js

我目前正在使用Backbone.js集合和View,我正在尝试将集合函数绑定到视图内的函数。我以为我可以简单地在集合中创建一个函数,然后将其绑定到视图中。不幸的是,它不断引用集合方法。这是我的代码。

var RightPaneCollectionView = Backbone.View.extend({
    initialize: function(){
        _.bindAll(this, 'render', 'add', 'remove', 'remove_by_name');   // bind the methods to this scope
        this.el.html("");   // clear out the view
        this.collection.bind('removeByName', this.remove_by_name);
                    this.collection.bind('remove', this.remove);
    },
    remove_by_name: function(){ console.log("Removing by name inside view.")
    }
}

var RightPaneCollection = Backbone.Collection.extend({
   model: RightPaneButtonModel,
url: "",
removeByName: function(){
    console.log("Removing by name inside collection");
}
});

我希望能够做下降

 rightPaneCollection.removeByName("foo");

并让它引用该视图。我不确定我是否会以正确的方式解决这个问题。目前,通过引用视图内部的remove方法,删除工作正常。

谢谢你的帮助!

2 个答案:

答案 0 :(得分:4)

这是你在找什么?

基本上,当项目被删除时,我从集合中触发“removeByName”事件,并且我传递了已删除项目的名称。在视图中,我绑定到该事件名称并调用视图的函数并访问要删除的项目的名称。

var RightPaneCollectionView = Backbone.View.extend({
    initialize: function(){
        _.bindAll(this, 'remove_by_name');
        this.el.html("");   // clear out the view
        this.collection.bind('removeByName', this.remove_by_name);
    },
    remove_by_name: function(name){ 
        console.log("Removing by name inside view: " + name)
    }
}

var RightPaneCollection = Backbone.Collection.extend({
   model: RightPaneButtonModel,
   url: "",
   removeByName: function(name){
       var itemToRemove = this.find(function(item){return item.get("name") === name;});
       if(itemToRemove) {
           this.remove(itemToRemove);
           this.trigger("removeByName", name);
       }
   }
});

答案 1 :(得分:1)

我不确定,但你不必手动触发事件吗?

var RightPaneCollection = Backbone.Collection.extend({
    model: RightPaneButtonModel,
    url: "",
    removeByName: function(){
        console.log("Removing by name inside collection");
        this.trigger('removeByName');
    }
});