您的位置:首页 > Web前端 > JavaScript

JavaScript自定事件-原生代码

2015-09-01 16:27 597 查看
var Events = function(){
this._listeners = {};//存储事件类型对象列表 { log:[fn,fn,...],show:[fn,fn,fn....],hide:[fn,fn,fn...]}
}
Events.prototype = {
/**
* 添加事件监听
* @param type 事件名称 [string]
* @param  fn 处理函数 [function]
* @return  [object]
*/
addEventListener:function(type,fn){
if(typeof type !== 'string'){
return;
}
if(typeof this._listeners[type] === 'undefined'){
this._listeners[type] = [];
}
if(typeof fn ==='function'){
this._listeners[type].push(fn);
}

return this;
},
/**
* @param type 事件类型 [string]
* @return [obj]
*/
fireEvent:function(type){
if(!type){
return;
}
var temp = {
fire:function(){
if(eventArray instanceof Array){
for(var i=eventArray.length-1;i>=0;i--){
eventArray[i]();
}
}
}
};
var eventArray;// 事件类型
if(typeof type ==='string'){ // 单类数据类型
eventArray = this._listeners[type];
temp.fire();
}else if(type instanceof Array){// 注意数组不能使用typeof 进行判断
for(var j=type.length-1;j>=0;j--){
eventArray = this._listeners[type[j]];
temp.fire();
}
}
return this;
},
/**
* @param type 事件名称 [string]
* @param fn 处理函数,跟监听的函数是一样的才行 [function]
* @return [obj]
*/
removeEventListener:function(type,fn){
if(!type || typeof type!=='string' || typeof fn !=='function'){
return;
}
var eventArray = this._listeners[type];
if(eventArray instanceof Array){
for(var i=eventArray.length-1;i>=0;i--){// 逐个遍历,删除匹配事件类型的函数
if(eventArray[i] === fn){
this._listeners[type].splice(i,1);
}
}

if(this._listeners[type].length<1){
delete this._listeners[type]; // 如果该类事件没有处理函数了,直接删除掉
}
}
return this;
}
};


测试

var e = new Events();

function show(){
alert('xxx');
}
e.addEventListener('show',show);//添加事件监听
e.fireEvent('show'); // 触发事件
// e.removeEventListener('show',show);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: