mlsteeves
mlsteeves

Reputation: 1271

Marionette CollectionView re-render when a model is removed from the collection

I figured out my problem, but I would like to know why, so that I may (hopefully) understand Marionette/backbone better.

Problem The code below does update the view when an item is removed:

var MainView = Marionette.ItemView.extend({
    template: "#sample-template",
    events :{
        "click #remove" : "remove"
    },
    remove: function(){            
        this.trigger("property:remove", this.model);
    }
});
var CollectionView = Marionette.CollectionView.extend({
    itemView: MainView,
    initialize: function(){
        this.on("itemview:property:remove", function(view, model){
            alert(this.collection.length);
            this.collection.remove(model);
            alert(this.collection.length);
        });
    }
});

A JsFiddle to view in all its glory

The fix The code below does update the view as expected:

var MainView = Marionette.ItemView.extend({
    template: "#sample-template",
    triggers :{
        "click #remove" : "property:remove"
    },
});

var CollectionView = Marionette.CollectionView.extend({
    itemView: MainView,
    initialize: function(){
        this.on("itemview:property:remove", function(view, model){
            alert(this.collection.length);
            this.collection.remove(view.model);
            alert(this.collection.length);
        });
    }
});

The jsFiddle

Upvotes: 3

Views: 5119

Answers (2)

mix3d
mix3d

Reputation: 4333

For anyone who comes across this, keep in mind that Marionette 2.x changed itemview to childview. Tripped me up a bit. Cheers!

Upvotes: 4

Chris Camaratta
Chris Camaratta

Reputation: 2779

Backbone.View defines a method called remove that removes a view from the DOM. Your first example overrides that method.

If you rename remove to something like removeIt the name collision disappears and the code works as expected. For what it's worth, I think the second approach is preferable for this type of situation anyway.

Upvotes: 5

Related Questions