I have a backbone collection and when I remove a model from the collection, I want it to remove the item from a list in the view.
My collection is pretty basic
MyApp.Collections.CurrentEvents = Backbone.Collection.extend({
model: MyApp.Models.Event
});
and in my views I have
MyApp.Views.CurrentEventItem = Backbone.View.extend({
el: 'div.current_event',
initialize: function(){
event = this.model;
_.bindAll(this, "remove");
MyApp.CurrentEvents.bind('remove',this.remove); //the collection holding events
this.render();
},
// yeah, yeah, render stuff here
remove: function(){
console.log(this);
$(this.el).unbind();
$(this.el).remove();
}
});
when I remove the model from the collection, it triggers the remove function, but the view is still on the page.
In the console, I can see the model, but I believe the model should have an ‘el’, but it doesn’t.
My container code is
MyApp.Views.CurrentEventsHolder = Backbone.View.extend({
el: 'div#currentHolder',
initialize: function(){
MyApp.CurrentEvents = new MyApp.Collections.CurrentEvents();
MyApp.CurrentEvents.bind('new', this.add);
},
add: function(){
var add_event = new MyApp.Views.CurrentEventItem(added_event);
$('div#currentHolder').append(add_event.el);
}
});
for some reason in the add method I can’t seem to use the $(this.el) before the append, though I’m not sure if that is the problem.
PROBLEM:
MyApp.CurrentEvents.bind('remove',this.remove);This triggers the
remove()function every time any model is deleted from the collection.This means that anytime a model is deleted, all the
CurrentEventItemview instances will be deleted.Now, about the view still being on the page:
It must have something to do with the way you appended/added/html-ed the view in the page. Check your other views, maybe if you have a
CurrentEventsContainerview of some sort, check your code from there because with your current code, it does delete the view, albeit, all of them though.RECOMMENDED FIX:
change your bindings to:
and make sure that when you instantiate it, pass on the
modelso that each view will have a corresponding model to it like so:This makes things a lot easier to manage in my opinion.
UPDATE (from your updated question)
The reason you aren’t able to use
this.elis because you haven’t passed the right context into theadd()function. You need to add_.bindAll(this,'add')in yourinitialize()function to pass the right context, therefore making yourthiscorrect, allowing you to usethis.elwithin theaddfunction. Also, change your code to this:MyApp.CurrentEvents.bind('new', this.add, this);this passes the right context. Also, why not useaddinstead as an event?