javascript 自定义事件
文章目录
javascript的自定义事件,还是很有趣的,也很灵活。
就相当于,我不知道你要干什么,什么时候干,但是我监听这个动作。
只要你有这个动作,OK,那么就可以去执行。
下面是代码:
;(function(window){
function Liu(){
this.arr = {};
}
Liu.fn = Liu.prototype;
Liu.fn.on = function(type,fn){
if(!this.arr[type]) this.arr[type] = [];
this.arr[type].push(fn);
};
Liu.fn.fire = function(event){
if(!event.target) event.target = this;
if( this.arr[event.type] instanceof Array){
for(let i=0,len=this.arr[event.type].length;i<len;i++){
this.arr[event.type][i](event);
}
}
};
Liu.fn.off = function(type,fn){
if(this.arr[type] instanceof Array){
for(let i=0,len=this.arr[type].length;i<len;i++){
if(this.arr[type][i]==fn){
this.arr[type].splice(i,1);
return true;
}
}
}else{
return false;
}
};
Liu.fn.once = function(type,fn){
var self = this;
var fn1 = fn;
fn = function(event){
fn1(event);
self.off(type,fn);
}
self.on(type,fn);
};
window.liu = new Liu();
})(window);
其中,on 是事件监听,也可以说是添加事件。
fire是触发事件。
off是解除事件与事件处理程序的绑定。
once 是一次性绑定。
实际上不难,只是开拓了脑回路。
虽然,不知道内部的事件是如何实现的,但是,这样的自定义事件,给人很爽的感觉。
虽然,代码很少,但是却能实现很多的东西。
另外,实现的场景很重要。
你可以自定义事件,也可以去监听他。 但是,关键的是什么时候触发他。
^-^

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论