以编程方式触发的事件不适用于事件委托 [英] Programmatically fired events not working with event delegation

查看:88
本文介绍了以编程方式触发的事件不适用于事件委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人能帮助我弄清楚为什么在MooTools中使用事件委托(来自Element.Delegation类)时无法以编程方式触发事件,将非常感激.

Would really appreciate if anyone can help me figure out why I am unable to fire events programmatically when using event delegation in MooTools (from the Element.Delegation class).

有一个父级<div>,在某些子级<input>元素上具有一个change侦听器.当更改事件由用户操作触发时,父div上的处理程序将被触发,但是当我在任何子输入上使用fireEvent以编程方式将其触发时,则不会发生任何事情.基本设置是:

There is a parent <div> that has a change listener on some child <input> elements. When the change event is triggered by user actions, the handler on the parent div gets triggered, but when I fire it programmatically with fireEvent on any child input, nothing happens. The basic setup is:

<div id="listener">
    <input type="text" id="color" class="color" />
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​</div>​​​​​​​​​​​

js

$("listener").addEvent("change:relay(.color)", function() {
    alert("changed!!");
});

$("color").fireEvent("change"); // nothing happens

父div上的事件处理程序未调用.任何帮助表示赞赏.

The event handler on the parent div does not get called. Any help is appreciated.

相关问题:用fireEvent触发的事件在DOM树中是否完全冒泡?我当前的破解方法是在本机上调度正在运行的事件(尽管如此,但仍然是黑客)- http://jsfiddle. net/SZZ3Z/1/

Related question: Do events triggered with fireEvent bubble at all in the DOM tree? My current hack is to dispatch the event natively which is working (but a hack nonetheless) - http://jsfiddle.net/SZZ3Z/1/

var event = document.createEvent("HTMLEvents")
event.initEvent("change", true);
document.getElementById("color").dispatchEvent(event); // instead of fireEvent

推荐答案

按原样"不能很好地工作.事件冒泡(以及事件的程序触发)的问题在于,它可能需要使事件对象为真实",才能使其包含与中继字符串匹配的event.target.同样,document.id("color").fireEvent()将不起作用,因为颜色本身没有附加任何事件.

this won't work too well 'as is'. the problem with event bubbling (and with programmatic firing of events) is that it may need the event object to be 'real' in order for it to contain event.target that is being matched against the relay string. also, document.id("color").fireEvent() won't work as color itself has no event attached to it.

要解决此问题,您可以通过传递包含目标元素的事件对象来在父侦听器上伪造该事件,如下所示:

to get around this, you fake the event on the parent listener by passing an event object that contains the target element like so:

document.id("listener").fireEvent("change", {
    target: document.id("color")
});

实际操作中的视图: http://www.jsfiddle.net/xZFqp/1/

如果您在回调函数中执行诸如event.stop之类的操作,则您需要传递{target: document.id("color"), stop: Function.from},以此类推,以获取可能引用的所有事件方法,但事件委托代码目前仅对target感兴趣.

if you do things like event.stop in your callback function then you need to pass on {target: document.id("color"), stop: Function.from} and so forth for any event methods you may be referencing but the event delegation code is only interested in target for now.

这篇关于以编程方式触发的事件不适用于事件委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆