I am looking for an equivalent to .on() from jQuery in Mootools. The purpose is to dynamically bind events to elements that are appended to the page after user interactions.

有帮助吗?

解决方案

There are addEvent() and addEvents() methods that attach an event listener(s) to a DOM element. Check http://mootools.net/docs/core/Element/Element.Event for documentation.

其他提示

It helps if you understand how Event Delgation works.

Here is an example from the page:

// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click",function(e) {
    // e.target is the clicked element!
    // If it was a list item
    if(e.target && e.target.nodeName == "LI") {
        // List item found!  Output the ID!
        console.log("List item ",e.target.id.replace("post-")," was clicked!");
    }
});

As @dimitar pointed out relay() is the MooTools way to delegate. In the documentation you can see both some code examples and a jsfiddle.

The syntax would be:

parentElement.addEvent('click:relay(.targetClass)', function(){

Where parentElement is some element present in the page at the time the JS code is loaded, and .targetClass would be a class in the target element you want to have delegation for.

As pointed out, there is nice jsFiddle example in the MooTools page, here is another one, adapted from the first one.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top