Custom event listener in Javascript

Here is basic event listener system -framework less- to perform custom event sender/reciever system threw your application :

/* ************************************************************************

	Licence : LGPLv3

	Version: 0.1

	Authors: deisss

	Date: 2012-09-01

	Date of last modification: 2012-09-01

	Description: Basic event system
************************************************************************ */
/**
 * Custom event system
*/
function eventListener(){
	var __listeners = new Array(),
		u           = 'undefined',
		f           = 'function';

	/**
	 * Adding a listener to a specific message type
	 *
	 * @param type {String} The event name
	 * @param fn {Function} The function to attach
	*/
	this.addListener = function(type, fn){
		if(typeof(fn) === f){
			if(typeof(__listeners[type]) === u){
				__listeners[type] = new Array();
			}
			__listeners[type].push(fn);
		}
	}

	/**
	 * Removing a listener to a specific message type
	 *
	 * @param type {String} The event name
	 * @param fn {Function} The function to detach
	*/
	this.removeListener = function(type, fn){
		if(typeof(__listeners[type]) !== u){
			for(var i=0, j=__listeners[type].length; i<j; ++i){
				if(typeof(fn) === f && __listeners[type][i] === fn){
					__listeners[type].splice(i, 1);
				}
			}
			//At the end, we clear unused listeners array type
			for(var j=0; j<__listeners.length; ++j){
				if(__listeners[j].length < 1){
					__listeners.splice(j, 1);
				}
			}
		}
	}

	/**
	 * Call an event, according to it's type
	 *
	 * @param type {String} The event name to dispatch
	 * @param data {Object} Anything you want to pass threw this event
	*/
	this.dispatch = function(type, data){
		var f = __listeners[type];
		if(typeof(f) !== u){
			for(var i=0, l=f.length; i<l; ++i){
				f[i](data);
			}
		}
	}
}

var bus = new eventListener();

Now you can use the bus object like this :

//Creating a dummy function for testing
function busListener(data){
	console.log("event recieve");
	console.log(data);
}
//Attach function to the customChannel event
bus.addListener("customChannel", busListener);



//When you are ready, call the busSender to see the console appearing data
bus.dispatch("customChannel", {
	test:'hello',
	v:12
});

The object provide also a remove listener, use it like this :

bus.removeListener("customChannel", busListener);
Publicités

Un commentaire

  1. Pingback: Custom Event Listener | Javascript

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s

%d blogueurs aiment cette page :