簡體   English   中英

Backbone.js收集方法綁定

[英]Backbone.js Collection Method Binding

我目前正在使用Backbone.js集合和視圖,並且嘗試將集合函數綁定到視圖內部的函數。 我以為我可以在集合內部簡單地創建一個函數,然后在視圖內部綁定它。 不幸的是,它一直在引用collections方法。 這是我的代碼。

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方法,刪除操作可以正常工作。

感謝您的幫助!

這是你想要的?

基本上,刪除項目時,我會從集合中觸發“ 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);
       }
   }
});

我不確定,但是您不必手動觸發事件嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM