Created
January 15, 2016 13:13
-
-
Save psychoss/8ee7df7c6fb86e83b6c4 to your computer and use it in GitHub Desktop.
Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var event = {//发布-订阅功能 | |
clientList: [], | |
listen: function(key, fn){ | |
if(!this.clientList[key]){ | |
this.clientList[key] = []; | |
} | |
this.clientList[key].push(fn); //订阅的消息添加进缓存列表 | |
}, | |
trigger: function(){ | |
var key = Array.prototype.shift.call(arguments), | |
fns = this.clientList[key]; | |
if(!fns || fns.length === 0){//如果没有绑定对应的消息 | |
return false; | |
} | |
for(var i=0, fn; fn = fns[i++];){ | |
fn.apply(this, arguments);//arguments是trigger时带上的参数 | |
} | |
}, | |
remove: function(key, fn){ | |
var fns = this.clientList[key]; | |
if(!fns){ | |
return false; | |
} | |
if(!fn){ | |
fns && (fns.length =0);//如果没有传入具体的回调函数,表示需要取消key对应消息的所有订阅; | |
}else{ | |
for (var l=fns.length-1; l>=0; l--){ | |
var _fn = fns[l]; | |
if(_fn === fn){ | |
fns.splice(l,1); | |
} | |
} | |
} | |
} | |
}; | |
var installEvent = function(obj){//给对象安装发布-订阅功能 | |
for (var i in event){ | |
obj[i] = event[i]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment