I've been learning more about prototype.js, and have today solved two long outstanding JavaScript challenges. I'm sure many others have already solved these problems, but I hadn't yet, so here they are.
Up to this point I've not used modern event handling to any great degree. I've got a fair understanding of the right way to do it and the IE way to do it, the problems with the differences in bubbling, etc. But what I hadn't seen before is a way to pass an argument to a function attached in this manner, and without that I had dismissed the whole premise as pretty useless. But to the rescue come anonymous functions, allowing you to pass a reference to a complex function as a function.
I'm no good at explaining this stuff, here's an example using prototype's event handling (feel free to use your own, the arguments are pretty constant):
Event.observe(window, 'load', pageLoaded, false);
That calls the function pageLoaded() when the document renders. But what if you want to pass an argument, or call multiple functions. Here's how:
Event.observe(window, 'load', function() { pageLoaded(); console.log("it worked!"); }, false);
(That's assuming that you have Firebug installed, otherwise replace console.log with alert)
My second issue is how do you observe a change in the value of a field when the user does not change the field directly? When JavaScript changes the value of a field the field does not trigger its onchange event. A common example of this is when somebody updates a date field using a popup calendar widget. In the past I would have had the calendar widget manually fire the onchange event, but that's rather codependent don't you think? Better to let the field worry about the field. Here's the prototype.js code that does the trick:
new Form.Element.Observer($("endDate"), 1, repopulateDateRanges);
What that does is create a specialized form of a prototype "TimedObserver" to watch the field with id="endDate", testing it every 1 second to see if it has changed, and if it has to fire the function repopulateDateRanges(). If you think about it at all you can see how easily that could be written with a recursive window.setTimeout function, but isn't it nice to let the prototype developers worry about that?
1 comment:
your a genius! I spent hours trying to figure out a way pass arguments to event handlers
Post a Comment