php設計模式--觀察者模式(4.1)面向過程完成頁面內容切換

觀察者模式 也叫通知 監聽者模式 

如果沒有設計模式我們只能一個一個改,新加一個就要改一次方法

 

<html>
<title>觀察者模式</title>
<style>
 div{ width: 200px;height: 50px; border: 1px solid #ccc;}
</style>

<body>
    <select name="sel" id="sel">
        <option value="0">男式風格</option>
        <option value="1">女式風格</option>
    </select>
	   <input type="button" onclick="drop()" value="不引起廣告的變化">
    <div id="test1">11</div>
    <div id="test2">22</div>
    <div id="test3">廣告</div>
</body>
<script>
/*var t=[];
console.log(t.length); //打印長度爲0
t[t.length]='1'; //相當於 t[0]='1'
console.log(t.length);//打印長度爲0
console.log(t);//打印 出數組
*/
    var sel = document.getElementById('sel');
    sel.observes = [];
    //添加一個觀察者
    sel.attach = function(obj) {	
        this.observes[this.observes.length] = obj;
		//把對象放到數組裏  數組的下標從0開始 數組爲空時也就是 this.observes[0]=obj
    }
    //刪除一個觀察者
    sel.detach = function(obj) {
        for (var i = 0; i < this.observes.length; i+=1) {		   
            if (this.observes[i] === obj) {
                delete this.observes[i];
            }
        }
    }
    //onchange 改變的時候通知
    sel.onchange = sel.notify = function() {
        for (var i = 0; i < this.observes.length; i+=1) {
            //循環通知 需要改變的   
            this.observes[i].update(this);
        }
    }
    //需要改變的
    var test2 = document.getElementById('test2');
    test2.update = function(sel) {
        if (sel.value == '1') {
            this.innerHTML = '化妝品';
        } else if (sel.value == '0') {
            this.innerHTML = '汽車 機械';
        }
    }
    test3.update = function(sel) {
        if (sel.value == '1') {
            this.innerHTML = 'test3的女 口紅';
        } else if (sel.value == '0') {
            this.innerHTML = 'test3的男0 足球';
        }
    }
    sel.attach(test2); //調用改變
    sel.attach(test3);
	//刪除監聽
	function drop(){
	 sel.detach(test3);
	}
	
</script>

</html>

 

 

 

原理就是註冊一個數組,把需要監聽的放到數組裏面 然後for循環調用改變 這樣就靈活了 

 

/****/

理解

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章