Notifier in Javascript

Every want to build a notification system, that will notify other classes when some thing happen in one object.

//notifier class
var notifier = function(){
	var notifierInstance = function(){
		
		//event collection
		/*
			eventCollection = {
				"event1": [
					function(args){},
					function(args){ console.log(args); }
				],
				"event2": [
					function(args){},
					function(args){ console.log(args); }
				]
			}	
		*/
		var eventCollection = {};

		this.addEventName = function(name){
			if(!eventCollection.hasOwnProperty(name)){
				eventCollection[name] = null;
			}
			else{
				throw "Event name already exists.";
			}
		}

		this.addEvent = function(name, handler){
			if(eventCollection.hasOwnProperty(name)){
				if(eventCollection[name] == null){
					eventCollection[name] = [];
				}
				var isAlreadyExist = false;
				for(var i = 0; i < eventCollection[name].length; i++){
					if(eventCollection[name][i] === handler){
						isAlreadyExist = true;
						break;
					}
				}
				if(!isAlreadyExist){
					eventCollection[name].push(handler);
				}
				else{
					//raise an exception
					throw "Handler already subscribed for this event";
				}
			}
			else{
				throw "Event is not available for broadcast."
			}
		}

		this.raiseEvent = function(name, args){
			if(eventCollection[name]){
				eventCollection[name].forEach(function(fn){
					fn(args);
				});
			}	
		}
	}

	this.getInstance = function(){
		if(notifier.instance){
			return notifier.instance;
		}
		else{
			notifier.instance = new notifierInstance();
			return notifier.instance;
		}
	}

	return this.getInstance();

}
notifier.instance = null;


//event names collection
var eventNames = {
	emitterEvent: "emitterEvent",
	withComplexObj: "withComplexObj"
}

//observer...listening to events
var observer = function(){

	var n = new notifier();

	this.print = function(arg){
		console.log("print:", arg)
	}
	this.print1 = function(arg){
		console.log("print1:", arg)
	}

	this.Subscribe = function(){
		n.addEvent(eventNames.emitterEvent, this.print);
		n.addEvent(eventNames.emitterEvent, this.print1);

		n.addEvent(eventNames.withComplexObj, this.print)		
	}
}

//class that will raise events
var emitter = function(){
	var eventName = "dummy";
	var n = new notifier();

	this.Emit = function(){
		n.addEventName(eventNames.emitterEvent);
		n.addEventName(eventNames.withComplexObj);		
	}

	this.add = function(val){
		n.raiseEvent(eventNames.emitterEvent, val);
	}

	this.sendComplexObj = function(obj){
		n.raiseEvent(eventNames.withComplexObj, obj);
	}
}

var emit = new emitter();
var obs = new observer();

//create new event channel
emit.Emit();
//subscribe to events
obs.Subscribe();

emit.add('adding 1');
emit.add('adding 2');

var obj = { 
		a: 'a',
		b: {
			c: 'c'
		}
	};

emit.sendComplexObj(obj);


Add Comments :

Login

Register