Forum Moderators: open

Message Too Old, No Replies

(Advanced) Event Handler Question

Adding instructions stored in variable to an event

         

vol7ron

4:35 pm on Dec 3, 2008 (gmt 0)

10+ Year Member



Use this code for reference:
   function attachEventHandlers(obj, eventType, fn, useCapture){
if (obj.addEventListener) {
obj.addEventListener(eventType, fn, useCapture);
return true;
} else if (obj.attachEvent) {
var val = obj.attachEvent("on"+eventType, fn);
return val;
} else {
try {
obj.eval("on" + eventType) = fn;
} catch (err) {
return;
}
}
}
function init(){
replace = "getObjById('outputID').innerHTML='hello';";
attachEventHandlers(document.links[e]
, 'click'
, function (replace){this.replace;}
, false
);
}

I cut some code out, but the init function is basically what I'm trying to do. replace is a variable that will have the command I want to add to the event.

So in the given example, when link[0] is clicked, I want the element with outputID to display 'hello'. Does that make sense?

I've tried with eval(), but that seems to do it at runtime and not when the event is triggered (link is clicked). Also, just to let you know getObjById is a universal function I created to retrieve the ID, much like getElementById. It works, so don't worry about that.

Thanks for any help,
vol7ron

vol7ron

6:40 pm on Dec 3, 2008 (gmt 0)

10+ Year Member



Curious if anyone knows how to do this?

Doing function (replace){alert(replace);} gets me a message box with '[object MouseEvent]'
Doing function (replace){eval(replace);} doesn't do anything.. it doesn't even give me a javascript error (probably because replace is undefined. I've also tried doing this.replace, which doesn't matter.

vol7ron

7:49 pm on Dec 3, 2008 (gmt 0)

10+ Year Member



In case anyone would like to hear (or even if I ever question it again), I found the solution:

instead of using function(replace){this.replace;} all I need is new Function(replace)

So init will look like:

   function init(){
replace = "getObjById('outputID').innerHTML='hello';";
attachEventHandlers(document.links[e]
, 'click'
, new Function(replace)
, false
);
}

Hope that helps,
vol7ron

__