Skip to content

Instantly share code, notes, and snippets.

@miensol
Last active December 16, 2015 13:08
Show Gist options
  • Save miensol/5439035 to your computer and use it in GitHub Desktop.
Save miensol/5439035 to your computer and use it in GitHub Desktop.
Javascript Observable
var Observable = function(){
var that = this,
listeners = {},
callHandler = function(args){
this.handler.apply(this.scope, args);
},
on = function(eventName, handlerFun, scope){
var listenerList = [], handlerObj;
if(!eventName){
throw "cannot call 'on' with empty eventName";
}
if(!handlerFun){
throw "cannot call 'on' with empty handlerFun";
}
listenerList = listeners[eventName] = listeners[eventName] || listenerList;
listenerList.push(handlerObj = {
handler: handlerFun,
call: callHandler,
scope: scope || that
});
return function(){
var index = listenerList.indexOf(handlerObj);
if(index != -1){
listenerList.splice(index,1);
}
};
},
fireEvent = function(eventName, rest){
var args = [].splice.call(arguments,0),
name = args.splice(0,1),
listenerList = [], index;
if(!name){
throw "cannot call 'fireEvent' with no eventName";
}
if(listeners[name]){
listenerList = listeners[name];
}
for(index = 0;index < listenerList.length; index += 1){
listenerList[index].call(args);
}
};
that.on = on;
that.fireEvent = fireEvent;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment