PDA

View Full Version : Custom Events: Best way?



blm126
08-07-2008, 08:53 PM
Ok, so I'm working a project where it is helpful to have custom events. This is how I'm doing it.


var hooks = {//Custom events object
hooks: {},//Store an event handler
add: function(hook,func){
//Add function func to handle hook
var oldhook = this.hooks[hook] || false;
this.hooks[hook] = oldhook ? function(data){oldhook(data);func(data);} : func;
},
call: function(hook,data){
//Call a hook
this.hooks[hook] && this.hooks[hook](data);
}
};

It works, but I keep thinking the use of closures here is a bad idea. Does anyone know what kind of performance hit this code would have?

DimX
08-07-2008, 09:33 PM
It would be better to store arrays of handlers for each hook type and then simply iterate the array and call all handlers. To add a handler you would simply add it to the corresponding array.

Example:


var hooks = {//Custom events object
hooks: {},//Store an event handler
add: function(hook,func){
//Add function func to handle hook
var hooksArr = this.hooks[hook];
if (!hooksArr)
hooksArr = this.hooks[hook] = new Array();
hooksArr.push(func);
},
call: function(hook, data){
var hooksArr = this.hooks[hook];
if (!hooksArr) return;
for (var i = 0; i < hooksArr.length; ++i)
hooksArr[i](data);
}
};