window.onload= function() {
function Emitter() {
this._listener = [];//_listener[自定义的事件名] = 所用执行的匿名函数
}
//注册事件
Emitter.prototype.bind = function(eventName, callback) {
var listener = this._listener[eventName] || [];
listener.push(callback);
this._listener[eventName] = listener;
}
//触发事件
Emitter.prototype.trigger = function(eventName) {
var args = Array.prototype.slice.apply(arguments).slice(1);atgs为获得除了eventName后面的参数
var listener = this._listener[eventName];
if(!Array.isArray(listener)) return;//自定义事件名不存在
listener.forEach(function(callback) {
try {
callback.apply(this, args);
}catch(e) {
console.error(e);
}
})
}
//实例
var emitter = new Emitter();
emitter.bind("myevent", function(arg1, arg2) {
console.log(arg1, arg2);
});
emitter.trigger(‘myevent‘, "a", "b");
}
原文:http://www.cnblogs.com/pcd12321/p/5223347.html