event-pubsub/event-pubsub.js

117 lines
2.3 KiB
JavaScript
Raw Normal View History

2014-02-18 20:47:21 -08:00
function sub(type,handler){
2016-07-11 04:34:27 -07:00
if(!handler){
var err=new ReferenceError('handler not defined');
throw(err);
}
2014-02-18 20:47:21 -08:00
checkScope.apply(this);
2014-02-18 20:47:21 -08:00
if(!this._events_[type])
this._events_[type]=[];
2014-02-18 20:47:21 -08:00
this._events_[type].push(handler);
}
function unsub(type,handler){
if(!handler){
var err=new ReferenceError('handler not defined. if you wish to remove all handlers from the event please pass "*" as the handler');
throw err;
}
2014-02-18 20:47:21 -08:00
checkScope.apply(this);
if(handler=='*'){
delete this._events_[type];
return;
2014-03-01 03:23:59 -08:00
}
2014-02-18 20:47:21 -08:00
if(!this._events_[type])
return;
for(var i=0,
2014-03-01 03:23:59 -08:00
count=this._events_[type].length;
2014-02-18 20:47:21 -08:00
i<count;
2014-03-01 03:23:59 -08:00
i++
){
if(this._events_[type][i]==handler){
this._events_[type].splice(i,1);
}
}
if(this._events_[type].length<1){
delete this._events_[type];
2014-02-18 20:47:21 -08:00
}
}
function pub(type){
checkScope.apply(this);
2014-02-18 20:47:21 -08:00
if(this._events_['*'] && type!='*'){
var params=Array.prototype.slice.call(arguments);
params.unshift('*');
this.trigger.apply(this,params);
}
2014-02-18 20:47:21 -08:00
if(!this._events_[type])
return;
for(var i=0,
events=this._events_[type],
2014-02-18 20:47:21 -08:00
count=events.length,
args=Array.prototype.slice.call(arguments,1);
i<count;
2014-02-18 20:47:21 -08:00
i++){
events[i].apply(this, args);
}
}
function checkScope(){
if(!this._events_)
this._events_={};
}
function init(scope){
if(!scope)
return {
on:sub,
off:unsub,
trigger:pub
};
2014-02-18 20:47:21 -08:00
scope.on=(
function(scope){
return function(){
sub.apply(
scope,
2014-02-18 20:47:21 -08:00
Array.prototype.slice.call(arguments)
);
}
}
)(scope);
2014-02-18 20:47:21 -08:00
scope.off=(
function(scope){
return function(){
unsub.apply(
scope,
2014-02-18 20:47:21 -08:00
Array.prototype.slice.call(arguments)
);
}
}
)(scope);
2014-02-18 20:47:21 -08:00
scope.trigger=(
function(scope){
return function(){
pub.apply(
scope,
2014-02-18 20:47:21 -08:00
Array.prototype.slice.call(arguments)
);
}
}
)(scope);
2014-02-18 20:47:21 -08:00
scope._events_={};
}
module.exports=init