简体   繁体   中英

Backbone.js Collection Method Binding

I am currently using Backbone.js collection and View and I am attempting to bind a collections function to a function inside of the view. I thought that I could simply create a function inside of the collection and then bind it inside of the view. Unfortunately, it keeps referencing the collections method. Here is my code.

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");
}
});

I'd like to be able to do the falling

 rightPaneCollection.removeByName("foo");

and have it reference the view. I'm not sure I'm going about this in the correct manner. Currently the remove works correctly by referencing the remove method inside of the view.

Thanks for you help!

Is this what you are looking for?

Basically, I am triggering a "removeByName" event from the collection when the item is removed and I pass the name of the item that was removed. In the View, I am binding to that event name and calling the view's function and accessing the name of the item being removed.

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);
       }
   }
});

I'm not certain, but don't you have to manually trigger the event?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM