Fixed my event class

Here's the updated code which should work all the time.

var EventList = new Array();
var g_eventIndex = 0;

function Event(obj, type){
if (obj._eventIndex){
if (EventList[obj._eventIndex][type]) return;
}
else
obj._eventIndex = g_eventIndex++;

if (typeof(EventList[obj._eventIndex]) == "undefined")
EventList[obj._eventIndex] = new Array();

EventList[obj._eventIndex][type] = true;
this.handlers = new Array();
this.type = type;
this.obj = obj;
this.obj._event = new Array();
this.obj._event[type] = this;

if (typeof(this.obj.addCustomEvent) != "function"){
this.obj.addCustomEvent = function(type, fn){
if (typeof(fn) == "function"){
this._event[type].handlers.push(fn);
return true;
}
return false;
}
}

this.raise = function(sender, args){
for(var i = 0; i < this.handlers.length; i++){
this.handlers[i](sender, args);
}
}
}

// addEvent(obj, "event", func);


function addEvent(obj, evType, fn, useCapture){
if (typeof(obj._eventIndex) == "number" && EventList[obj._eventIndex][evType] && obj.addCustomEvent){
var r = obj.addCustomEvent(evType, fn);
return r;
}
else if (obj.addEventListener){
obj.addEventListener(evType, fn, useCapture);
return true;
} else if (obj.attachEvent){
var r = obj.attachEvent("on"+evType, fn);
return r;
} else {
alert("Handler could not be attached");
}
}


Now it will handle events of the same name in different objects. I just didn't want to have to come up with different names for events in different objects that did nearly the exact same thing.

I was reading a bit on the internets about how people do this type of thing. I read a post on Yahoo! that said the YUI event handling mechanism is "only 2KB". This is 55 lines with liberal white spacing. The thing about computer science is that sure, there might be something out there that does what you need it to do, and you can get it for free, but it's gonna do tons of other stuff that you really don't need. Not yet anyway. Same goes for software in general. If you need a simple photo editor, you're not gonna pay $600 for Photoshop when iPhoto will do (part of a $79 package with tons of other neat software, which also is overkill if you don't need that other stuff). So, if I need something very specialized, small, and easy to use, I'll write it. If you need this as well, feel free to use mine directly or for knowledge. It's not big or special, but will be used as part of a big and special project :) That will come soon.

blog comments powered by Disqus