自定义事件

1.自定义事件,其实就是事件的监听,触发,是设计模式中的观察者模式。主要有三个方法:on,off,emit。

基本实现如下:

Array.prototype.remove = function(item){
var temp = [];
var index;
for(var i=0; i<this.length;i++)
{

if(this[i]==item)
{
index = i;
break;
}
}
if(typeof index!="undefined")
this.splice(index,1);
return this;
}

function MyEvent()
{
this.listener=[];
}
MyEvent.prototype = {
on:function(type,fn){

if(this.listener[type]&&Object.prototype.toString.call(this.listener[type])=="[object Array]")
{
this.listener[type].push(fn);
}
else
{
this.listener[type]=[];
this.listener[type].push(fn);
}
},
off:function(type,fn)
{
if(this.listener[type]&&Object.prototype.toString.call(this.listener[type])=="[object Array]")
{
if(Object.prototype.toString.call(fn)=="[object Function]")
{
this.listener[type].remove(fn);
}
else
{
this.listener[type]=[];
}
}
},
emit:function(type){
if(this.listener[type]&&Object.prototype.toString.call(this.listener[type])=="[object Array]")
{
for(let i of this.listener[type])
{
i();
}
}
}
}

var myEvent = new MyEvent();
myEvent.on("click", clickFn);
myEvent.emit("click");
myEvent.off("click", clickFn);
myEvent.emit("click");
function clickFn()
{
console.log("clickFn");
}

猜你喜欢

转载自www.cnblogs.com/chillaxyw/p/9357669.html