Skip to content

Instantly share code, notes, and snippets.

@MrTrick
Last active December 12, 2015 05:08
Show Gist options
  • Save MrTrick/4719582 to your computer and use it in GitHub Desktop.
Save MrTrick/4719582 to your computer and use it in GitHub Desktop.
Events - only calls the first handler, unregisters them afterwards. * before.js shows the vanilla backbone implementation. * in model.js shows the helper function * after.js shows the new implementation.
action.oncefirst( {
'cancel' : function(msg) {
...
},
'error' : function(msg) {
...
},
'complete;' : function(data) {
...
}
});
action.run(context);
var oncancel = function(msg) {
...
cleanup();
};
var onerror = function(msg) {
...
cleanup();
};
var oncomplete = function(data) {
...
cleanup();
};
var cleanup = function() {
action.off('cancel', oncancel);
action.off('error', onerror);
action.off('complete', oncomplete);
};
action.on('cancel', oncancel);
action.on('error', onerror);
action.on('complete', oncomplete);
action.run(context);
/**
* Given an event map, register each event handler.
*
* If any of those events are triggered, unregister all the given handlers.
*
* Returns the unregister function - call if the given handlers should be removed before any are triggered.
*/
oncefirst: function(listeners) {
var unregister = function() { this.off(listeners); };
this.once( _.keys(listeners).join(' '), unregister );
this.on(listeners);
return unregister;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment