自定义事件实现bind,unbind,trigger方法
2016-11-08 本文已影响0人
一个小小实习生
class Emit {
constructor(){
this.name = 'Emit';
this._linstener = {};
}
bind(type,callback){
let linstener = this._linstener[type] || [];
linstener.push(callback);
this._linstener[type] = linstener;
}
trigger(type,callback){
if(typeof type !== 'string') throw new Error('EventName Error');
if(typeof callback === 'function'){
let args = Array.prototype.slice.call(arguments,2);
this._linstener[type].forEach(function(item,index){
if(item === callback){
item.apply(this,args);
return false;
}
}.bind(this))
}else{
let args = Array.prototype.slice.call(arguments,1);
this._linstener[type].forEach(function(item,index){
if(typeof item !== 'function') throw new Error('CallBack is not a Function');
item.apply(this,args);
}.bind(this))
}
}
unbind(type,callback){
if(typeof type !== 'string') throw new Error('EventName Error');
if(this._linstener[type] === undefined) return;
if(typeof fn === 'function'){
this._linstener[type].forEach(function(item,index){
if(item === fn){
this._linstener[type].splice(index,1);
return false;
}
}.bind(this))
}else{
delete this._linstener[type];
}
}
}
//测试
var event = new Emit();
//console.log(event)
function a(a){
alert(a)
}
event.bind('click',a)
console.log(event)
function b(b){
alert(b)
}
event.bind('click',b)
//event.unbind('click',b)
event.trigger('click',a,'a')
event.trigger('click',b,'b')
console.log(event)