Lives: 30

Dynamically Assigning Event Handlers w/ Arguments to Instance Methods in Javascript

Posted Fri Feb 16, 2007 @ 1:34 PM

I ran into a speed bump of sorts when attempting to assign an object instance method as a DOM event handler, there's some information floating around the net, but a post on the topic can't hurt. Something like this on the server side would usually fit the bill:

spaghetti.Attributes.Add("onmousemove",this.Id+".myMouseMoveHandler(event)");

However since we want to create this same result completely on the client-side we'll need to do this in the class constructor, something like this:

document.getElementById('spaghetti').onmousemove = this.myMouseMoveHandler;

May work in some situations, but arguments cannot be passed when assigning this way, also, unless the handler function is defined within the constructor it won't be available yet. Something like this:

document.getElementById('spaghetti').onmousemove = 
   new Function ('e',id+'.myMouseMoveHandler(e);');

Again will only work if the handler method has been defined within the constructor, but at least an argument may be passed. Next we add the dreaded eval so it can be evaluated on the fly, allowing us to define the handler method for the object instance outside of the constructor:

document.getElementById('spaghetti').onmousemove = 
   new Function ('e','eval("'+id+'.myMouseMoveHandler(e);");');

Figured it was just convoluted enough to warrant a blog post.

Posted to Phil Tucker by phil

Posted on Fri Feb 16, 2007 @ 1:34 PM

Filed under: , ,

Comments

Posted on Fri Feb 16, 2007 @ 1:34 PM
If you're working with MS AJAX I believe Function.createDelegate will give you the functionality you require. If your not using MS AJAX I beleive this code block works stand-alone. Also Nikhi Kothari's UpdateControls library has similar functionalty: http://www.nikhilk.net/UpdateControls.aspx
Blake
Posted on Fri Feb 16, 2007 @ 1:34 PM
Phil, I'm sorry to be bothering you in your comments section, but I'm getting incessant "malformed formal parameter" errors whenever I try to dynamically assign an event handler to dynamicall-recreated element. I say "recreated" because all I'm trying to do is unset a file input field in IE...that's another story... Any thoughts on why this doesn't work? document.getElementById(sField).onchange = new Function(sField, 'eval("' + sField + '.jToggleImageClear(sField);");'); ("jToggleImageClear" is the name of a preexisting function). Thanks for any insights you can provide!!!
Anonymous comments are not allowed. Click here to log in or create an account.

Copyright © 2010 ComponentArt, Inc. All rights reserved.