码迷,mamicode.com
首页 > 其他好文 > 详细

自定义事件

时间:2018-07-24 00:47:31      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:ons   eve   方法   obj   else   bre   typeof   return   ret   

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

自定义事件

标签:ons   eve   方法   obj   else   bre   typeof   return   ret   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!