热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

事宜绑定机制简朴完成

道理:保护一个事宜数组经由过程apply挪用varslice[].slice;**eventcontrolclass*@param{context}*functionEvent(c

道理:

  • 保护一个事宜数组

  • 经由过程apply挪用

var slice = [].slice;
/*
* event control class
* @param {context}
*/
function Event(ctx){
this._ctx = ctx || this;
this._events = {};
}
var EventProto = Event.prototype;
/*
* bind a event
* @param {event} eventType
* @param {fn} function
*/
EventProto.on = function(event, fn){
this._events[event] = this._events[event] || [];
this._events[event].push(fn);
return this;
}
/*
* bind an event but only called one time
* @param {event} eventType
* @param {fn} function
*/
EventProto.Once= function(event, fn){
var self = this;
//when fn is called, remove all event listener
function fnWrap(){
self.off(event, fnWrap);
fn.apply(this, arguments);
}
//to specifiy remove method
fnWrap.fn = fn;
this.on(event, fnWrap);
return this;
}
/*
* unbind an event
* @param {event} eventType
* @param {fn} function
*/
EventProto.off = function(event, fn){
//remove all events
if(!arguments){
this._events = {};
return this;
}
//there are not fn binded
var events = this._events[event];
if(!events) return this;
//remove an type events
if(arguments.length === 1 && typeof event === 'string'){
delete this._events[event];
return this;
}
//remove fn
var handler;
for(var i = 0; i handler = events[i];
if(handler === fn || handler.fn === fn){
events.splice(i, 1);
break;
}
}
return this;
}
/*
* emit
* @param {event}
* @param {fn param}
*/
EventProto.emit = function(event){
var events = this._events[event],
args;
if(events){
events = events.slice(0);
args = slice.call(arguments, 1);
events.forEach(function(event){
event.apply(this._ctx, args);
})
}
return this;
}

推荐阅读
author-avatar
乐乐
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有