Let’s say I have some models in a collection and views with events bound to them. An easy way to append this to the DOM is using a ‘one-liner’.
$('body').html(new MyView({ collection: new MyCollection() }).el);
Note here that the model has event listeners (CRUD), the collection has some, and the view has some.
Now we are done with this view, and we want to change the view. We can do something like this.
$('body').html(new MyNextView({ collection: new MyNextCollection() }).el);
Now on the page there are all the new elements, but all the old elements are still in place. We need a way to unbind all the events from all the objects.
Is there a way to achieve this.
—
I know this would be possible if you keep an array with all the objects stored. That way you can loop trough the array and unbind all the events from all the object. I am just wondering if this is possible with anonymously created objects.
If you can reference the view’s element (e.g. because you know the id), then calling
$(el).remove()will remove the view from the DOM and should remove any DOM-based event bindings (as long as the view isn’t listening to DOM elements outside itsel).But that does’t necessarily mean it’ll be removed from memory – you may still need to watch for and deal with other references to the view and the collection.