mootools
Events play a huge role in JavaScript. I can't name one website I've created in the past two years that hasn't used JavaScript event handling on some level. Ask yourself: how often do I inject elements into the DOM and not add an event to them? For me it's very rare. For this reason I'm proud and excited for the release of code.
事件在JavaScript中扮演着重要的角色。 我无法命名过去两年中创建的一个未在某种程度上使用JavaScript事件处理的网站。 问问自己:我多久将元素注入DOM而不向其中添加事件? 对我来说,这非常罕见。 因此,我为代码的发布感到自豪和兴奋。
WTF是事件委托吗? (WTF is Event Delegation?)
Event delegation is the process of assigning an event listener to a parent for all of its children instead of assigning the same event to every child.
事件委托是将事件侦听器为其所有子级分配给父级的过程,而不是将相同的事件分配给每个子级的过程。
一些示例HTML (Some Sample HTML)
A list with 3 list item elements which contain a link. For the sake of my example, this list will have list items added to it and we want an alert to pop up any time a link within the list is clicked.
具有3个包含链接的列表项元素的列表。 就我的示例而言,此列表将添加列表项,并且我们希望在单击列表中的链接时弹出警报。
MooTools JavaScript事件委托语法 (The MooTools JavaScript Event Delegation Syntax)
window.addEvent('domready',function() { /* delegate */ document.id('link-list').addEvent('click:relay(a)', function(e){ e.stop(); alert('you clicked a link!'); }); /* Add link to show event delegation works! Notice how we haven't assigned an event to this specific element. We already added the event to the list element itself */ document.id('add-link').addEvent('click',function() { var li = new Element('li').inject('link-list'); var link = new Element('a',{ text:'David Walsh Blog', href:'https://davidwalsh.name'}).inject(li); });});
All you need to do is add :relay to the parent selector and place the "children" match inside the relay pseudo selector. You'll probably question how :relay works because the ":" syntax is used for pseudo selectors. The Element.Delegation JavaScript download overwrites the addEvent, removeEvent, and fireEvent methods to accommodate for the :relay syntax.
您需要做的就是在父选择器中添加:relay并将“子项”匹配项放置在中继伪选择器中。 您可能会质疑:relay的工作原理,因为“:”语法用于伪选择器。 JavaScript.Element.Delegation下载将覆盖addEvent,removeEvent和fireEvent方法以适应:relay语法。
事件委托取代了... (Event Delegation Replaces...)
var links = document.id('link-list').getElements('li');links.each(function(link) { link.addEvent('click',function() { //assign actions here });})
Why collect and iterate through elements to add events when you can simply use event delegation?
当您可以简单地使用事件委托时,为什么要收集并遍历元素以添加事件呢?
Event delegation is a great way to avoid repeating the same event assignments for elements within a parent element, especially when you are adding elements into the page dynamically. If you've not upgraded to MooTools 1.2.4 yet, I hope this is just the kick in the pants you need!
事件委托是避免对父元素中的元素重复相同的事件分配的好方法,尤其是在将元素动态添加到页面中时。 如果您尚未升级到MooTools 1.2.4,我希望这只是您需要的裤子!
翻译自:
mootools