Static News Archive



   (21-Apr-08 23:37)  Simple Js problem and solution
If you are messing about with javascript classes, then you may come across a situation where you want to pass a javascript function call to a method as a callback.

For example:

function myRoutine(callback) {
var anchor = document.createElement('a');
anchor.onclick = callback;
//....e.t.c.
}


Simple enough right? just pass the name of the callback that you want to call when the anchor tag is clicked without the brackets and everything is fine.


Now suppose that the callback we want to call takes an argument:

function runMeOnClick(message) {
alert("clicked: " message);
}


how do you pass the function with arguments?

You can't do :

myRoutine(runMeOnClick('hello!'));


because the function runMeOnClick is called straight away.

Instead, pass the function in as a string, and use eval() to do the rest:


myRoutine("runMeOnClick('hello!')");

function myRoutine(callback) {
var anchor = document.createElement('a');
anchor.onclick = function () { eval(callback); } ;
//....e.t.c.
}



Easy!
Post a comment     

<-  (27-Mar-08 18:26)  Showing a dialog in ... (28-Apr-08 0:02)  A few solutions to s...  ->













(sitemap)