← Back Home

发布-订阅模式(观察者模式)

  1. JavaScript

观察者模式定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会得到通知。

普通示例

var Event = (function() {

	var clientList = {},
		listen,
		remove,
		trigger;

	listen = function(key, fn) {
		if(!clientList[key]) {
			clientList[key] = [];
		}
		clientList[key].push(fn);
	}

	remove = function(key, fn) {
		var fns = clientList[key];
		if(!fns || fns.length == 0) {
			return false;
		}
		if(!fn) {
			fns && fns.length = 0;
		}else {
			for(var i = 0, l = fns,length; i < l; i++) {
				var _fn = fns[i];
				if(fn === _fn) {
					clientList[key].splice(i, 1);
				}
			}
		}
	}

	trigger = function() {
		var key = Array.prototype.slice.call(arguments),
			fns = clientList[key];
		if(!fns || fns.length === 0) {
			return false;
		}
		for(var i = 0, l = fns.length; i < l; i++) {
			fn.apply(this, arguments);
		}
	}

	return {
		listen: listen,
		trigger: trigger,
		remove: remove
	}

})()

观察者模式广泛应用于一步编程中,这是一种代替异步回调的方案。

异步示例

$.ajax('http://xxx.com/login', function(data) {
	Event.trigger('loginSucc', data);
});

var header = (function() {
	Event.listener('loginSucc', function(data) {
		header.setAvator(data);
	});
	return {
		setAvator: function(data) {
			console.log('更新头像数据');
		}
	}
})();

观察者模式适用于模块间的通信

模块间的通信

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>模块间的通信</title>
</head>
<body>
	<button id="count">点我</button>
	<div id="show"></div>
	<script type="text/javascript">
		var a = (function() {
			var count = 0;
			var button = document.getElementById('count');
			btn.click = function() {
				Event.trigger('add', count++);
			}
		})();

		var b = (function() {
			var div = document.getElementById('show');
			Event.listener('add', function(count) {
				div.innerHTML = count;
			})
		})();

	</script>
</body>
</html>
comments powered by Disqus