views:

643

answers:

2

How do I make elements that are loaded via ajax, adopt the events associated with the same class on mootools 1.11?

As far as I know, in jQquery, if your ajax response consists of something like <div class='button'>,
if there is an event bind using live to $('.button'), those events would automatically bind.

Is that possible with MooTools 1.11?

+3  A: 

Perhaps something like this might do what you're looking for? Though I'm not sure if it'll work with 1.11.

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'); });
anomareh
A: 

anomareh is on the right track.

You would also want to check the ancestor elements of the event target.

I'm not sure if this works with all events since some of them do not bubble (not sure how Mootools handles this).

Sean Hogan
I think document.body is the whole document, no?
Thorpe Obazee
That is true but irrelevant because anomareh's code only checks if the event target matches the selector, whereas jQuery's `live()` also checks ancestors of the event target.
Sean Hogan