3
Element.implement({
    addLiveEvent: function(event, selector, fn){
        this.addEvent(event, function(e){
            var t = $(e.target);

            if (!t.match(selector)) return false;
                fn.apply(t, [e]);
        }.bindWithEvent(this, selector, fn));
    }
});

$(document.body).addLiveEvent('click', 'a', function(e){ alert('This is a live event'); });

The above code was done in a similar question to implement .live behaviour in Mootools. I've read the question: Prototype equivalent for jQuery live function.

How do I implement this in Prototype? Probably something that can be implemented like this:

document.liveobserve('click', 'a', function(e){ alert('This is a live event');

Edited to make the question clear.

Community
  • 1
  • 1
Teej
  • 12,764
  • 9
  • 72
  • 93
  • 2
    To be honest, in mootools (even though this is flaky in the current release), it now works natively / differently, for instance: `$('foo').addEvent('click:relay(li)');` - not sure if this helps matters with prototype though. – Dimitar Christoff Mar 05 '10 at 12:27
  • @Dimitar. that's nice to know +1 – Teej Mar 05 '10 at 12:37

1 Answers1

0

The simplest (and perhaps not the fastest or best) way would appear to be something like:

Element.live = function(evType, evSelector, evBlock) {
  var mySelector = evSelector;
  var myBlock = evBlock;
  this.observe(evType, function(ev) {
    if (ev.target.match(mySelector)) {
      evBlock(ev);
    }
  });
};

The parameters evSelector and evBlock are assigned to local variables so the they are available to the event handler (It's a closure). The passed block evBlock gets passed the event object just like a normal Prototype event handler.

It should be noted this is going to handle every event of type 'evType' so if it's a mouseMove/mouseOver this is going to make your page slow. Also FireBug will probably just go to sleep on you due to the number of events that it has to single step through.

EDIT: Changed as per comments

Haqa
  • 476
  • 3
  • 14
  • I believe this code doesn't require the element on which the event fires to be a descendant of the one on which `.live` was called, something that jQuery does do. You're only checking if the event targets matches `evSelector`, and should also check if it's a descendant of `self` (set to `this` in the outer function, as the observe call won't have the same bound object anymore). – Gijs Jun 26 '11 at 10:29
  • Good point, but performing the observe on this instead of document should solve that, shouldn't it? – Haqa Jun 26 '11 at 16:03