Skip to content

Instantly share code, notes, and snippets.

@werelax
Created April 15, 2014 15:58
Show Gist options
  • Save werelax/10743724 to your computer and use it in GitHub Desktop.
Save werelax/10743724 to your computer and use it in GitHub Desktop.
A nice way to gain some control over Backbone.View#events callbacks
// Use invoker to generate the invoker directly
// and be able to manipulate it. The key is that
// the invoker allways invokes on "this".
var invoker = function(method) {
var args = [].slice.call(arguments, 1);
return function() {
var newargs = [].slice.call(arguments);
return this[method].apply(this, args.concat(newargs));
};
};
// Surprisingly useful little combinator
var k = function(v) {
return function() { return v; };
};
// Headers
var EditableHeader = Base.ItemView.extend({
template: JST["components/bookingspopup/editable-header"],
events: {
// now you can manipulate your callback functions easely
"keyup .item-room input": _.debounce(invoker("fetchRoomInfo"), 1000),
// this is just to cancel unwanted default behavirous (text selection)
"mousedown .ctrl-add, .ctrl-subs": k(false),
// and configure invocations without duplication
"click .ctrl-add": invoker("alterPax", 1),
"click .ctrl-subs": invoker("alterPax", -1),
},
alterPax: function(delta, e) {
e.preventDefault();
var currentPax = this.model.get("pax");
this.model.set({pax: currentPax + delta}, {validate: true});
this.render();
return false;
},
fetchRoomInfo: function() {
console.log("FETCH ROOM INFO...");
}
});
@werelax
Copy link
Author

werelax commented Apr 15, 2014

Is very obvious now that I think about it, but I see this direct invocator generation as a really useful way to manipulate the event handlers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment