Neatening up custom event handlers - remove need for 'event' parameter
I'm building some objects that will trigger custom events, and I'm using jQuery's bind and trigger to manage this for me, like so:
function MyObject() {
var _this = this;
this.onUpdate = function(fn) {
$(_this).bind('MyObject.update', fn);
};
this.update = function(params) {
//Do stuff...
$(_this).trigger('MyObject.update', [updatedID]);
};
}
My problem is when I come to register other callback functions with onUpdate - the functions I pass in need to include the 'event' parameter for trigger开发者_如何转开发 to work correctly, like so:
function myCallback(event, updatedID) {
//Do more stuff...
}
var myobject = new MyObject();
myobject.onUpdate(myCallback);
Is there a nice way I can wrap the function that I pass in to bind in the onUpdate method, so that myCallback doesn't need the 'event' parameter, as it seems a bit irrelevant for my purposes?
You could use apply
[MDN]:
this.onUpdate = function(fn) {
$(_this).bind('MyObject.update', function() {
var params = [].slice.call(arguments, 1); // remove first argument
fn.apply(this, params);
});
};
OT: Instead of adding the functions to each instance, you should extend the functions prototype:
MyObject.prototype.onUpdate = function(fn) {...};
MyObject.prototype.update = function(params) {...};
This way, all the instances share these functions.
Articles that are worth to be read in this regard:
- MDN - Working with Objects
- MDN - Details of the object model
- MDN - Inheritance revisited
精彩评论