1. 发布-订阅模式
var observe = (function(){
var events = {},
listen,
trigger,
remmove;
listen = function(key,fn){
if(!events[key]){
events[key] = [];
}
events[key].push(fn);
};
trigger = function(){
var key = Array.prototype.shift.call(arguments);
var fns = events[key];
if(!fns || fns.length === 0){
return false;
}
for(var i=0,fn;fn=fns[i++];){
fn.apply(this,arguments);
}
};
remove = function(key,fn){
var fns = events[key];
if(!fns){
return false;
}
if(!fn){
fns && (fns.length=0);
}else{
for(var l =fns.length -1;l>=0;l--){
var _fn = fns[l];
if(_fn===fn){
fns.splice(l,1);
}
}
}
};
return {
listen:listen,
trigger:trigger,
remove:remove
}
})();
- observe.listen(‘xx‘,function(price){
console.log(price);
});
observe.trigger(‘xx‘,2000);
时间: 2024-10-11 11:00:05