arkitrave log

arkitrave :: log

4/25/2006

Passing parameters into your AddEvent call

Filed under:

If, like me, you’re still using some variant of an addEventListener function to add DOM events, you may run into the need to pass parameters into the function that you’re calling. (Just for the record, I use Angus Turnbull’s Add Event Manager, as it lets me use the this keyword in the functions it calls).

My event listeners are set up like this (my addEvent script is in a helper object called EventHelper):

EventHelper.AddEvent(window, 'load', foo, false);

Let’s say you’re using prototype-based JavaScript. In this case, this should refer to the “class” your function is a part of. As soon as you write any event handler call, the scope of this changes to the event itself (click, mouseover, etc) for that line of code.

Let’s say we need to pass parameters to foo in the line of code above. In addition to whatever parameters the function needs, we probably need to pass three additional items: the element the handler is attached to, the correct object scope of this and the event reference itself.

The code looks like this:

var thisReference = this;
EventHelper.AddEvent(elementReference, 'click',
pointer = function(e) {thisReference.foo(this,
thisReference, other, parameters, e); }, false);

thisReference stores the correct this scope to a variable - this is the scope of the prototype object. We’ll lose it otherwise when we write the AddEvent line. elementReference, obviously, is the element that the event handler is being attached to. e is the event, which needs to be passed into the pointer function if it’s going to be available to pass into foo(). The fun part is the pointer function. We are setting up an anonymous function which has the click event as its parameter. This pointer function is only used to call the actual function (foo) you want attached to the event. You can use it to pass whatever parameters you want to foo; just make sure you pass this, thisReference and e if you need the element, the prototype object and the event in the function you’re calling.

The pointer function gets the actual, original event (e). When the event happens and pointer is executed, it calls foo, passing it your parameters.

Enjoy.

Tags:,

638 Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.