views:

42

answers:

1

Particularly the bit about live....

 jQuery('.something').live('click', function() {
     jQuery(this).parent('form').reset();
 });

I suppose this might work as well, though I am curious about the parent function:

 jQuery('.something').live('click', function() {
     this.form.reset();
 });
+3  A: 

Live

Prototype doesn't currently have "live" support. You can do something similar with event delegation, though. That's where you watch for the event on a parent element, and then in the event handler find out which child element the event actually happened on:

$('theFormID').observe('click', handleFormClick);
function handleFormClick(event) {
    var element;

    // Get the element on which the click occurred
    element = event.findElement();
}

Event delegation is only possible with events that bubble (like 'click'); I don't know if jQuery's live stuff has that same issue.

One nice thing is that you can pass CSS selectors into Event#findElement:

$('tbodyID').observe('click', handleTableClick);
function handleTableClick(event) {
    var element;

    // Get the element on which the click occurred
    element = event.findElement('tr');
}

...which finds the tr that was clicked, even if the actual click occurred within a span inside a td inside the tr.

Proper use of event delegation can dramatically simplify hooking/unhooking elements, particular when you're adding and removing elements dynamically.

I wouldn't be surprised if there's a plug-in for Prototype that does "live" support.

Parent

You mentioned that you want to get the parent of the clicked control. When you hook up a handler with Prototype, by default it sets things up so that within your handler, this references the element on which you've set the event handler. So for instance, if you have a div with the id foo:

$('foo').observe('click', function(event) {
    // Here, `this` will refer to the `foo` element
});

You can then use Prototype's Element#up to get the parent element. (If you're using event delegation and you hook the event on the parent in the first place, of course just use this directly and if you also need to get a reference to the thing that was clicked, use #findElement as above.)

T.J. Crowder
I love Prototype
Thorpe Obazee
TJ, I believe there's some discussion in adding a .live implementation in Prototype. Would it be saved for a major release?
Thorpe Obazee
@Thrope: I think there is a plan to do it, yes. I don't know which release they're targeting it for, but I wouldn't be surprised if it were 1.7. You could ask here, it will get in front of the right eyes: http://groups.google.com/group/prototype-scriptaculous
T.J. Crowder