Skip to content

Instantly share code, notes, and snippets.

@pea3nut
Last active September 20, 2016 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pea3nut/af111bd14f3f46b34d5f7f98e4e7a70f to your computer and use it in GitHub Desktop.
Save pea3nut/af111bd14f3f46b34d5f7f98e4e7a70f to your computer and use it in GitHub Desktop.
自定义的事件接口,作为其他类的父类使用,API接口与jQ很像
class PxerEvent{
constructor(eventList=[]){
this.eventList =eventList;
this._event ={};
this._oneEvent ={};
return new Proxy(this ,{
get(target ,property){
if(property in target){
return target[property];
};
let inEvent =target.eventList.some( item => property &&(item===property) );
if(inEvent){
return target.dispatch.bind(target ,property);
};
},
})
};
}
PxerEvent.prototype.on =function(type, listener){
if( !( this._checkEventType(type) && this._checkListener(listener) )) return this;
this._event[type] ||(this._event[type]=[]);
this._event[type].push(listener);
return this;
};
PxerEvent.prototype.one =function(type, listener){
if( !( this._checkEventType(type) && this._checkListener(listener) )) return this;
this._oneEvent[type] ||(this._oneEvent[type]=[]);
this._oneEvent[type].push(listener);
return this;
};
PxerEvent.prototype.off =function(type, listener){
if( !( this._checkEventType(type) && this._checkListener(listener) )) return this;
if(type ==='*'){
this._event ={};
return this;
};
if(typeof listener ==='undefined'){
delete this._event[type];
return this;
};
let index =this._event[type].lastIndexOf(listener);
delete this._event[index];
return this;
};
PxerEvent.prototype._checkEventType =function(type){
let inEvent =this.eventList.some( item => type &&(item===type) );
if(!inEvent){
console.warn(`PxerEvent: "${type}" is not in eventList[${this.eventList}]`);
return false;
};
return true;
};
PxerEvent.prototype._checkListener =function(listener){
if(typeof listener !=='function'){
console.warn(`PxerEvent: "${listener}" is not a function`);
return false;
};
return true;
};
PxerEvent.prototype.dispatch =function(type ,data){
if(!this._checkEventType(type))return this;
if( Array.isArray(this._event[type]) &&this._event[type].length!==0){
this._event[type].forEach(function(item){
item.call(this ,data);
} ,this)
};
if( Array.isArray(this._oneEvent[type]) &&this._oneEvent[type].length!==0){
this._oneEvent[type].forEach(function(item){
item.call(this ,data);
} ,this);
delete this._oneEvent[type];
};
return this;
};
//测试代码
/*
class A extends PxerEvent{
constructor(){
super(['say']);
this.b=2;
}
}
var a =new A();
a.on('say' ,function(data){
console.log(this);
console.log(data);//kkk
console.log(this.b);//2
});
a.one('say' ,function(data){
console.log('one:'+data);
});
a.dispatch('say' ,'kkk');
a.say('kkk');
// 输出:*/
// A
// kkk
// 2
// one:kkk
// A
// kkk
// 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment