zoukankan      html  css  js  c++  java
  • 设计模式之观察者模式

    <!DOCTYPE html>
    <html lang="zh">
    <head>
    	<meta charset="utf-8"/>
    	<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"/>
    	<title> new document </title>
    	<style>
    		div {
    			padding: 10px;
    			 300px;
    			margin: 10px;
    			border: 1px solid #666666;
    		}
    	</style>
    </head>
    
    <body>
    <!-- html :begin -->
    <select name="selObs" id="selObs">
    	<option value="1">风格一</option>
    	<option value="2">风格二</option>
    </select>
    
    <div id="div1">this is div1</div>
    <div id="div2">this is div2</div>
    
    <input type="button" value="div2风格不变" id="notChange"/>
    <!-- html :end -->
    </body>
    <script src="jquery-1.8.2.min.js"></script>
    <script>
    	$(document).ready(function () {
    		var div1 = $('#div1'), div2 = $('#div2'), selO = $('#selObs');
    		selO.observers = {};
    		selO.addObserver = function (key, obs) {
    			this.observers[key] = obs;
    		};
    		selO.removeObserver = function (key) {
    			delete this.observers[key];
    		};
    		selO.notifyObs = function () {
    			for (var key in this.observers) {
    				this.observers[key].update(this);
    			}
    		};
    
    		selO.change(function () {
    			selO.notifyObs();
    		});
    
    		selO.addObserver('div1', div1);
    		selO.addObserver('div2', div2);
    
    		div1.update = function (o) {
    			if (o.val() == '1') {
    				$(this).css('background', 'red');
    			} else if (o.val() == '2') {
    				$(this).css('background', '#ccc');
    			}
    		};
    		div2.update = div1.update;
    
    		$('#notChange').on('click', function () {
    			selO.removeObserver('div2');
    		});
    
    
    	});
    </script>
    
    </html>
    

      

  • 相关阅读:
    CSS面试题总结
    HTML面试题总结
    JS中如何删除某个元素下的所有子元素(节点)?
    JS apply() call() bind()方法的使用
    JS小游戏--贪吃蛇
    Tensorflow——tf.train.exponential_decay函数(指数衰减法)
    自定义属性
    JS中兼容代码总结---更新中
    测试flex的各种属性
    添加网络打印机_批处理文件
  • 原文地址:https://www.cnblogs.com/tom-zhu/p/3506760.html
Copyright © 2011-2022 走看看