function test(){
this.list = {}
};
test.prototype = {
constructor:test,
add:function(key,fn){
if(typeof this.list[key] == 'undefined'){//检测hello是否存在
this.list[key] = [];
}
this.list[key].push(fn);//将hello加入事件数组
},
triggle:function(){
var key = Array.prototype.shift.call(arguments);//arguments为伪数组
var fns = this.list[key];//存在多个hello事件?
if(!fns || fns.length<=0)return;
for(var i=fns.length-1;i>=0;i--){
fns[i].apply(this,arguments);//依次执行所有的hello
}
}
}
var one = new test();
one.add('hello',function(tmp){
console.log(tmp)
})
one.triggle('hello','world')
one.triggle('hello','mdzz')
one.add('say',function(tmp){
console.log(tmp)
})
one.triggle('say','hi')
var two = new test();
two.add('biubiubiu',function(tmp){
console.log(tmp)
})
two.triggle('biubiubiu','boomboomboom!');
可以参考红皮书和JavaScript设计模式与开发实践