zoukankan      html  css  js  c++  java
  • JS实现简单的观察者模式

    <!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');

      

    有时间会更新一下。。。。。。

  • 相关阅读:
    安卓模拟器黑屏
    关系型数据库的1NF、2NF、3NF
    flowable数据库详解
    spring事务传播行为详解
    springboot整合activity
    各种java面试题目
    springCloud中增加gateway(超详细)
    mysql实现主从复制
    flowable整合springboot
    window安装linux系统
  • 原文地址:https://www.cnblogs.com/MainActivity/p/9094193.html
Copyright © 2011-2022 走看看