Skip to content

Instantly share code, notes, and snippets.

@SgtPooki
Created April 15, 2015 00:39
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 SgtPooki/a92e386c0c45d3406314 to your computer and use it in GitHub Desktop.
Save SgtPooki/a92e386c0c45d3406314 to your computer and use it in GitHub Desktop.
A module that decorates a passed in object with on, off, and trigger functions.
/**
* @fileOverview
* @author Russell Dempsey <SgtPooki@gmail.com>
* 2015
*/
'use strict';
var Decoration = {};
var observableDecorator = function observableDecorator(object) {
var i = 0;
var decoratorKeys = Object.keys(Decoration);
var length = decoratorKeys.length;
var keyName;
for (i; i < length; i++) {
keyName = decoratorKeys[i];
if (object[keyName] !== undefined) {
console.log(object);
throw Error('I am extremely simple, I refuse to handle your complex objects.');
} else {
object[keyName] = Decoration[keyName];
}
}
};
Decoration.listeners = [];
Decoration.on = function decorationOn(eventName, callbackFunction) {
if (this.listeners[eventName] === undefined) {
this.listeners[eventName] = [callbackFunction];
} else {
this.listeners[eventName].push(callbackFunction);
}
};
Decoration.off = function decorationOff(eventName, callbackFunction) {
var group = this.listeners[eventName];
var match = false;
var i = 0;
var length;
if (group === undefined) {
return false;
}
length = group.length;
if (callbackFunction !== undefined) {
for (i; i < length; i++) {
if (group[i] === callbackFunction) {
match = true;
group.splice(i, 1);
}
}
}
if (match === false) {
this.listeners[eventName] = [];
}
return true;
};
Decoration.trigger = function decorationTrigger(eventName, data) {
var group = this.listeners[eventName];
var i = 0;
var length;
if (group === undefined) {
return false;
}
length = group.length;
for (i; i < length; i++) {
group[i](data);
}
};
return observableDecorator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment