3)Javascript设计模式:Observer模式

Observer模式

var Observer = (function() {

	var instance = null;

	function Observe() {
		this.events = {}
	}

	Observe.prototype.subscribe = function(eventName, callback) {
		var actions = this.events[eventName];
		if( !actions) {
			actions = this.events[eventName] = [];
		}
		actions.push(callback);

	};

	Observe.prototype.publish = function(eventName) {
		var args = Array.prototype.slice.call(arguments).slice(1);
		var actions = this.events[eventName];
		if(actions) {
			for(var cb in actions) {
				actions[cb].apply(null, args)
			}
		}
		else {
			console.log(eventName || '' + ' is not registered');
		}
	};

	function returnFunction() {
		if(!instance) {
			instance = new Observe();
		}
		return instance;
	}

	returnFunction.toString = function() {
		console.log('Use Observer() to get instance');
	};

	return returnFunction;

})();

posted @ 2015-12-26 18:38  sexy_girl  阅读(299)  评论(0编辑  收藏  举报