JS实现简单的观察者模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | <!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><br><br><br><br><br><br> |
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');
有时间会更新一下。。。。。。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步