首页 > 其他 > 详细

自定义事件

时间:2018-07-24 00:32:15      阅读:189      评论:0      收藏:0      [点我收藏+]

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");
}

自定义事件

原文:https://www.cnblogs.com/chillaxyw/p/9357669.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!