Last active
August 29, 2015 14:05
-
-
Save maroshii/4024b1d1b483c061c388 to your computer and use it in GitHub Desktop.
Remove a Backbone view and make it listen/trigger events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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