Skip to content

Instantly share code, notes, and snippets.

@DomBlack
Created October 8, 2013 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DomBlack/6885740 to your computer and use it in GitHub Desktop.
Save DomBlack/6885740 to your computer and use it in GitHub Desktop.
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