Javascript: programatically creating methods to be called later
Asked by: misha 7 views technology
I want to call methods on a swf on a page, and pass into the methods a closure (aka an anonymous function). The closure is js, and needs to be called by the swf back out on the js page. The swf is doing it through:
ExternalInterface.call('method_name_on_js_side', stuff)
Now, I can’t happily pass the closure into the swf. This is because ExternalInterface is limited – it takes a function name as its first argument, no ifs or buts about it. So I gotta register the closure on the js side in a hash, then pass in its hash key into the swf – instead of the closure itself.
I’m using JS you can programatically register methods to use later. You can define functions up front, and call them later in time.
What I wanted to do was to call a function on an object that is a wrapper to another object. This wrapper would call the same method on the object it is wrapping as was called on it. In other words, when I call wrapper.func(), the wrapper calls wrapped.func().
var methods = {
'users': {'stuff'},
'accounts': {'stuff2'}
}
var wrap = function(method) {return function() { eval('wrapped.'+method+"()"); } }
for(var method in methods) {
wrapper[method] = wrap(method);
}
So above I have a hash that stores all the methods I want to end up with on the wrapper object. Then I defined the wrap method, which basically copies the value of method when its passed in, into a local method variable (at least I think so, otherwise how would it be stored?).
Then, when I create the wrapper, I iterate through all the methods and call the wrap method. Now, if I call wrapper.users() it will return an anonymous function
function() { eval('wrapped.'+method+"()"); }
This function will be immediately executed, and will call wrapped.users();
This actually works where as what I was trying before was a no-go. Before, I didn’t have the extra function wrap – I just did the eval right in the for loop. The problem was, eval was evaluating method and always getting ‘accounts’ – the last value method had. In the example at the top, method was not the latest value but whatever it was at the time the wrap method was called. Hence my thinking that its copied in that step and exists as a saved value in the anonymous function.
