Skip to content

Instantly share code, notes, and snippets.

@hagino3000
Created November 27, 2010 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hagino3000/717680 to your computer and use it in GitHub Desktop.
Save hagino3000/717680 to your computer and use it in GitHub Desktop.
Ovservable for JavaScript Classes
/**
* To class Observable
*
*/
function Observable() {}
Observable.prototype = {
/**
*
*/
initEvents : function(listeners) {
this.events = {};
listeners = listeners || {};
for (action in listeners) {
if (typeof(listeners[action]) == 'function' || listeners[action] instanceof Function){
this.on(action, listeners[action]);
} else {
this.on(action, listeners[action].fn, listeners[action].scope);
}
}
},
/**
* Fire event
*/
fireEvent : function(eventName/*, _opt event data */) {
var args = Array.prototype.slice.call(arguments);
var eventName = args.shift();
var fns = this.events[eventName];
if (fns) {
fns.forEach(function(f) {
f.fn.apply(f.scope, args);
});
}
},
/**
* Add event listener
*/
on : function(eventName, fn, scope) {
eventName = eventName.toLowerCase();
if (!this.events[eventName]) {
this.events[eventName] = [];
}
var fns = this.events[eventName];
fns.push({
fn : fn, scope : scope
});
},
/**
* Remove event listener
*/
un : function(eventName, fn, scope) {
eventName = eventName.toLowerCase();
var fns = this.events[eventName];
if (fns) {
for (var i=0; i<fns.length; i++) {
if (fns[i].fn == fn && fns[i].scope == scope) {
fns.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Remove all event listeners
*/
purgeListeners : function() {
this.events = {};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment