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)
自定义事件实现bind,unbind,trigger方法
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 这是我在简书的第二篇文章,一直以来都会想写些什么。但一个是怕,害怕写的不好而受到鄙视(想了半天不知道该用什么词,原...
- 一、如果让你实现属性的weak,如何实现的? PS: @property 等同于在.h文件中声明实例变量的get/...