Created
April 15, 2015 00:39
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @fileOverview | |
* @author Russell Dempsey <[email protected]> | |
* 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