/**
* __action_hook.js
* Desc: Class for easily handling callback functions
*/
var ActionHook;
(function () {
/* Private object properties */
var ActionHooks = {};
/* Private functions */
//Binds a function to an object - based on Function.bind from Prototype(www.prototypejs.org)
var BindFunction = function () {
var args = toArray(arguments);
var func = args.shift();
var obj = args.shift();
return function () {
return func.apply(obj, args.concat(toArray(arguments) ) );
}
}
//Converts any iterable object to an array - based on $A from Prototype(www.prototypejs.org)
var toArray = function (iterable) {
if (!iterable) return[];
if (iterable.toArray) return iterable.toArray();
var length = iterable.length, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}
/* ActionHook class */
ActionHook = function (Id) {
/* Private class properties */
var Actions = {};
var Instance = {
/* Public class functions */
//Adds a function to a specified action
Add: function (Action, fCallback, oScope) {
if (typeof Action === "undefined" || typeof fCallback !== "function") return false;
var fFunc = (typeof oScope === "undefined") ? fCallback : BindFunction (fCallback, this);
if (typeof Action === "object") {
var Result = true;
if (typeof Action.length === "number") {
for (var i=0; i<Action.length; i++) {
Result &= this.Add(Action[i], fFunc);
}
} else {
for (var i in Action) {
Result &= this.Add(Action[i], fFunc);
}
}
return(Result == true);
} else if (typeof Action === "string") {
if (typeof Actions[Action] === "object") Actions[Action].push(fFunc);
else Actions[Action] =[fFunc];
return true;
}
return false;
},
//Removes an action and all hooked functions
Remove: function (Action) {
if (typeof Action === "object") {
var Result = true;
if (typeof Action.length === "number") {
for (var i=0; i<Action.length; i++) {
Result &= this.Remove(Action[i]);
}
} else {
for (var i in Action) {
Result &= this.Remove(Action[i]);
}
}
return(Result == true);
} else if (typeof Action === "string") {
if (typeof Actions[Action] === "object") {
delete Actions[Action];
return true;
}
}
return false;
},
//Executes an action calling all hooked functions
Do: function () {
var args = toArray(arguments);
var Action = args.shift();
if (typeof Action === "object") {
var Result = true;
if (typeof Action.length === "number") {
for (var i=0; i<Action.length; i++) {
Result &= this.Do(Action[i]);
}
} else {
for (var i in Action) {
Result &= this.Do(Action[i]);
}
}
return(Result == true);
} else if (typeof Action === "string") {
if (typeof Actions[Action] === "object") {
for (var i=0; i<Actions[Action].length; i++) {
Actions[Action][i].apply(null, args);
}
return true;
}
}
return false;
},
//Destroys this action hook instance
Destroy: function () {
delete ActionHooks[Id];
}
};
ActionHooks[Id] = Instance;
return Instance;
}
})();