Wednesday, February 8th, 2006

Using Events in Prototype

Category: JavaScript, Programming, Prototype

Ecytemedia has an article on how to use Events in Prototype. It dives into attaching functions to events using Event.observe along with some advanced javascript using anonymous functions and closures. Check out the following code block:

javascript

  1. $$(this.list + " li").each(function(item) {
  2.       Event.observe(item, 'click', this.showTagName.bindAsEventListener(this));
  3.     }.bind(this));

Read this as “get all items for the list, binding the function “showTagName” to their onClick event, maintaining a reference to “this” (the element) inside the event function.

Now if you want to be able to tell showTagName to stop or start observing, maybe based on another user event, you have to extract the anonymous function to:

javascript

  1. this.showTagObserver = this.showTagName.bindAsEventListener(this);

and then the Event call becomes:

javascript

  1. Event.observe(item, 'click', this.showTagObserver);

We need to do this so we can refer to the observed function in multiple places, in order to have it turned off or on.

It might take a little bit to really grok what is going on here, but its well worth it.

Posted by Rob Sanheim at 7:00 am
1 Comment

++++-
4 rating from 52 votes

1 Comment »

Comments feed TrackBack URI

I’m having trouble getting the following code to work in IE7:

Event.observe(item, ‘mouseover’, eventHandler);

function eventHandler(e)
{
alert(‘x: ‘ + e.clientX + ‘\ny: ‘ + clientY);
}

Comment by tordnordell — March 30, 2009

Leave a comment

You must be logged in to post a comment.