这是总主机独立的,不需要的jQuery或DOM在这种情况下!
function CustomEvents(){
//object holding eventhandlers
this.handlers_ = {};
}
//check if the event type does not exist, create it.
//then push new callback in array.
CustomEvents.prototype.addEventListner = function (type, callBack){
if (!this.handlers_[type]) this.handlers_[type] = [];
this.handlers_[type].push(callBack);
}
CustomEvents.prototype.triggerEvent = function (type){
//trigger all handlers attached to events
if (!this.handlers_[type]) return;
for (var i=0, handler; handler = this.handlers_[type][i]; i++)
{
//call handler function and supply all the original arguments of this function
//minus the first argument which is the type of the event itself
if (typeof handler === "function") handler.apply(this,arguments.slice(1));
}
}
//delete all handlers to an event
CustomEvents.prototype.purgeEventType = function(type){
return delete this.handlers_[type];
}
测试:
var customEvents = new CustomEvents();
customEvents.addEventListner("event A", function(arg){alert('Event A with arguments' + arg);));
customEvents.triggerEvent("event A", "the args");
编辑添加参数传递
当然,如果你有JQuery的,无论如何,我相信你会找到其他地方,你会发现它*很有用。您还可以获得使用在无数开发人员的生产环境中经过测试和测试的代码的好处,而您自己的实现可能会遇到一些错误。此外,计算机变得越来越快,所以与@ Box9例子中更快实现的几行代码相比,实现自己的几毫秒页面载入的好处并不是那么好。 – jmort253 2011-01-07 01:28:21