var Event = (function(){
var global = this,
Event,
_default = 'defalut';
Event = function(){
var _listen,
_trigger,
_remove,
_slice = Array.prototype.slice,
_shift = Array.prototype.shift,
_unshift = Array.prototype.unshift,
namespaceCache = {},
_create,
find,
each = function(arr,fn){
var ret;
for(var i=0; i<arr.length; i++){
var n = arr[i];
ret = fn.call(n,i,n);
}
return ret;
};
//订阅事件,分类订阅消息
_listen = function(key,fn,cache){
if(!cache[key]){
cache[key] = [];
}else{
cache[key].push(fn);
}
};
//取消订阅
_remove = function(key,cache,fn){
if(cache[key]){
if(fn){
for(var i=cache[key].length; i>=0; i--){
if(cache[key][i] === fn){
cache[key].slice(i,1);
}
}
}
}else{
cache[key] = [];
}
};
//触发事件
_trigger = function(){
var cache = _shift.call(arguments), //传的第一个是cache
key = _shift.call(arguments), //再传一个key
args = arguments, //剩下的是参数
_self = this,
ret,
stack = cache[key];
console.log(stack);
if(!stack || !stack.length){
return ;
}
return each(stack,function(){
return this.apply(_self,args);
});
};
_create = function(namespace){
var namespace = namespace || _default;
var cache = {},
offlineStack = [],
ret = {
listen : function(key,fn,last){
_listen(key,fn,cache);
if(offlineStack === null){
return;
}
if(last === 'last'){
offlineStack.length && offlineStack.pop();
}else{
each(offlineStack,function(){
this();
});
}
offlineStack = null;
},
one : function(key,fn,last){
_remove(key,cache);
this.listen(key,fn,last);
},
trigger : function(){
var fn,args,_self = this;
_unshift.call(arguments,cache);
args = arguments;
fn = function(){
return _trigger.apply(_self, args);
};
if(offlineStack){
return offlineStack.push(fn);
}
return fn();
}
};
return namespace ? (namespaceCache[namespace] ? namespaceCache[namespace] : namespaceCache[namespace] = ret) : ret;
};
return {
create : _create,
one : function(key,fn,last){
var event = this.create();
event.one(key,fn,last);
},
remove : function(key,fn){
var event = this.create();
event.remove(key,fn);
},
listen : function(key,fn,last){
var event = this.create();
event.listen(key,fn,last);
},
trigger : function(){
var event = this.create();
event.trigger().apply(this,arguments);
}
};
}();
return Event;
})();
实现了一个发布订阅的抽象类。支持定义命名空间,先发布后订阅的情况。做一个记录
javascript学习——订阅发布抽象类
最新推荐文章于 2022-06-16 22:08:52 发布