Results 1 to 2 of 2

Thread: Custom Events: Best way?

  1. #1
    Join Date
    Sep 2005
    Posts
    882
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Custom Events: Best way?

    Ok, so I'm working a project where it is helpful to have custom events. This is how I'm doing it.
    Code:
    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?

  2. #2
    Join Date
    Jun 2006
    Posts
    182
    Thanks
    0
    Thanked 14 Times in 14 Posts

    Default

    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:
    Code:
    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);
    	}
    };
    Last edited by DimX; 08-08-2008 at 08:13 AM. Reason: example fixed

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •