Skip to content

Instantly share code, notes, and snippets.

@maroshii
Last active August 29, 2015 14:05
Show Gist options
  • Save maroshii/4024b1d1b483c061c388 to your computer and use it in GitHub Desktop.
Save maroshii/4024b1d1b483c061c388 to your computer and use it in GitHub Desktop.
Remove a Backbone view and make it listen/trigger events
/*
Make views listen and trigger events.
We wrap it under `ev` to avoid name conflicts.
Eg:
myView.ev.trigger('update');
myView.ev.on('update',function(){
console.log('view updated');
})
*/
Backbone.View.prototype.ev = _.extend({}, Backbone.Events);
/*
Remove a view and all events associated to it.
Useful to avoid having zombie views.
myView.close();
myView.ev.on('close',function(){
console.log('view closed');
})
*/
Backbone.View.prototype.close = function(e){
if(e && e.preventDefault) e.preventDefault();
try{
this.ev.trigger('close');
this.ev.off();
} catch(err) {}
this.remove();
this.unbind();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment