Created
October 8, 2013 14:37
-
-
Save DomBlack/6885740 to your computer and use it in GitHub Desktop.
Built based on; http://stackoverflow.com/questions/19245918/how-to-propagate-backbone-stoplistening-to-prevent-memory-leaks
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
define( | |
[ 'lib/underscore', 'lib/backbone' ], | |
function(_, Backbone) { | |
"use strict"; | |
/** | |
* An extension of the Backbone `off` method. | |
* | |
* This method will trigger <code>onNoObservers</code> when | |
* there are no more observers left. | |
*/ | |
function extendedOffMethod() { | |
Backbone.Events.off.apply(this, arguments); | |
//No events or no keys. | |
if ( (!this._events || _.isEmpty(this._events)) | |
&& typeof(this.onNoObservers) === 'function' | |
) { | |
this.onNoObservers(); | |
} | |
} | |
/** | |
* Callback for calling stopListening methods | |
*/ | |
function autoCloseCallback() { | |
this.stopListening(); | |
} | |
var module = { | |
/** | |
* Adds Events API extensions. | |
* | |
* Methods Added; | |
* <code>onNoObservers()</code> | |
* | |
* @param {Backbone.Events} eventsObj The events object to extend | |
*/ | |
extendEventsAPI: function(eventsObj) { | |
eventsObj.off = extendedOffMethod; | |
}, | |
/** | |
* Automatically close an object when nothing listens to it anymore. | |
* | |
* @param {Backbone.Events} eventsObj The events object to auto stop listening on | |
*/ | |
autoCleanup: function(eventsObj) { | |
module.extendEventsAPI(eventsObj); | |
eventsObj.onNoObservers = autoCloseCallback; | |
} | |
}; | |
return module; | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment