I have been working on a little project where I needed to store a set of functions to be executed within an inner html html element when an event is invoked in its parent page.
After some thought I decided to create a list of events which stores an array of functions to be executed from the parent. So I created the BindEvent function which sits in the parent and simply adds a function to the list of events mapped to the name of the event.
var Events = null;
function BindEvent(event, func) {
if (Events == null)
Events = new Array();
if (Events[event] == null)
Events[event] = new Array();
var len = Events[event].length;
Events[event][len] = func;
}
The next step is to create an invoke function that finds the event in the list and invokes the functions that have been bound to it. Again this was quite simple however it took me some Googling to work out how to execute a JavaScript function that is stored in a variable.
The answer is simple! To execute a JavaScript anonymous function that is stored in a variable: Just surround the variable name in braces and add a set of function call braces to the end of it! For example the second line here will execute the function:
var func = function () { document.writeln(“Hello World!”); };
(func)();
Ok back to the invoke event function. Here it is:
function InvokeEventFunctions(event) {
var func = Events[event];
for (var i = 0; i < func.length; i++) {
if (func[i] != null) {
(func[i])();
}
}
}
Now, with two simple functions and a multi dimensional array, we have a pretty powerful anonymous function binder and invoker. The beauty of using an anonymous function when binding is that you can call it from anywhere and it will encapsulate all the current variables at the DOM in which the function was created.
So in my case it was perfect as I had a set of processes that needed to be run native to an inner html element when something happens on its parent. The events where bound from the child (document.parent.BindEvent(event, func)) so when the Invoke function is executed in the parent and it in turn executed a function created in the inner html therefore it will use the DOM of the inner html no DOM of the parent page.
For more information and a slightly different method check out Daniel’s answer on StackOverflow here.
