<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="box"> 点我发布事件 </div> <script src="js/jquery-2.1.0.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> var pubSub = function(){}; pubSub.prototype.threadPool = []; pubSub.subscribe = function(name,cb){ pubSub.prototype.threadPool.push({ name:name, fun:cb }); } pubSub.publish = function(name){ var threadPool = pubSub.prototype.threadPool; for (var i in threadPool) { setTimeout(function(i){ if(threadPool[i]['name']==name){ threadPool[i]['fun'](); } }(i),0); } } $("#box").click(function(){ pubSub.publish('dateChange'); }) pubSub.subscribe('dateChange',function(){ this.name = 'lisi' console.log('hello world') }) pubSub.subscribe('dateChange',function(){ this.name = 'zhangsan' console.log('这是我订阅的第二个方法') }) </script> </body> </html>
var PubSub = function(){
this.threadPool = [];
this.subscrib = function(name,fun){
this.threadPool.push({
name:name,
fun:fun
});
}.bind(this);
this.publish = function(name){
this.threadPool.forEach(function(v,i){
if(v['name']==name){
v['fun']();
}
});
}.bind(this);
};
var p = new PubSub();
p.subscrib('hello',function(){console.log('hello1')});
p.subscrib('hello',function(){console.log('hello2')});
p.publish('hello');
有时间会更新一下。。。。。。