Created
October 31, 2012 18:52
-
-
Save twalker/3989070 to your computer and use it in GitHub Desktop.
zombie killer: a backbone view mixin
This file contains hidden or 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
/** | |
* View mixin to properly cleanup dom, backbone, and custom event listeners. | |
* A view zombie killer. | |
* e.g. myView.destroy(); OR destroyable.destroy.call(myView); | |
* | |
* CAVEAT: | |
* Although custom events will stop triggering, custom event listeners | |
* are not automatically removed since the binding context is unknown. e.g. | |
* otherView.on('foo', thisView.doSomething, thisView); | |
* | |
* Custom event listeners should be removed in the same context where the | |
* listener was attached, by listening to the 'destroy' event. e.g. | |
* | |
* thisView.on('destroy', function(){ | |
* otherView.off('foo', thisView.doSomething); | |
* // or, for convenience | |
* thisView.offOf(otherView); | |
* }); | |
* // or as a cryptic one-liner: | |
* thisView.on('destroy', thisView.offOf.bind(thisView, otherView)); | |
* | |
**/ | |
define([], function(){ | |
return { | |
// removes event listeners from dom, model, and collection. | |
// also stops firing custom events. | |
destroy: function(){ | |
var view = this; | |
// remove model or collection bindings | |
if(view.model) view.model.off(null, null, view); | |
if(view.collection) view.collection.off(null, null, view); | |
// trigger last event before destruction--so custom bindings can be removed. | |
view.trigger('destroy', view); | |
// stop triggering custom events | |
view.off(); | |
// remove event listeners (delegates to jQuery.empty() for view work) | |
view.remove(); | |
}, | |
// removes event listeners from the provided object. | |
// obj argument should be a backbone object that extends events. | |
offOf: function(obj){ | |
obj.off(null, null, this); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
don't need this garbage with backbone v.0.9.9's introduction of
listenTo
.