设计模式之观察者模式

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

			width: 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>

  

你可能感兴趣的:(观察者模式)