Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #11060 (new enhancement)

Opened 2 years ago

Last modified 2 years ago

[PATCH] Basic Event delegation

Reported by: patnakajima Assigned to: sam
Priority: normal Milestone: 2.x
Component: Prototype Version: edge
Severity: normal Keywords: events observe delegate
Cc:

Description

I've attached a patch that introduces the beginnings of event delegation to Prototype. The syntax is quite similar to that of Event.observe, with the only difference being an additional parameter that contains a CSS selector. This selector is used to check whether or not an element should receive the delegated handler.

Here's an example of its use. The following code will cause the onclick event for child elements of $('all') to be handled by the Behaviors.cancel handler, as long as they have the class name "cancel". This is beneficial, as obviously any elements that are added to the page dynamically will still receive this behavior, without any sort of handler refresh necessary.

var Behaviors = {
  cancel: function(event){
    // Perform cancellation tasks
    event.stop()
  }
}

$('all').delegate('click', '.cancel', Behaviors.cancel)

My implementation of Event.delegate only handles events that bubble, therefore "onsubmit" is woefully missing (until I get around to simulating it via a custom event). It's also missing the ability to unregister delegators, though I wonder if that might be alright for now, since delegators probably don't need to be created/destroyed nearly as frequently as handlers.

I added two new tests to the unit tests for Event, though I'm a bit new to unit testing for Javascript libraries, and the coverage could probably be improved. Any help here would be terrific.

Attachments

event-delegation.diff (2.3 kB) - added by patnakajima on 02/08/08 22:58:07.

Change History

02/08/08 22:58:07 changed by patnakajima

  • attachment event-delegation.diff added.

02/09/08 06:07:05 changed by patnakajima

  • summary changed from Basic Event delegation to [PATCH] Basic Event delegation.