简体   繁体   English

YUI3:我该如何触发事件?

[英]YUI3: How would I trigger an event?

Suppose I have a click event on a link/button/etc. 假设我在链接/按钮/等上有一个单击事件。

var myButton = Y.one('.button');

myButton.on('click', function() {
   // code
});

There is something else happening on the page that I want to trigger a click event on this button. 我想在此按钮上触发点击事件,因此页面上发生了其他事情。 How would I do this? 我该怎么做?

I saw YUI3's fire() method, but it looked like that was designed for custom events. 我看到了YUI3的fire()方法,但它看起来像是为自定义事件设计的。 If I am supposed to use fire(), then will myButton.fire('click') work? 如果我应该使用fire(),那么myButton.fire('click')工作?

(I'm looking for the equivalent of jQuery's .trigger() method, which works on DOM events or custom events.) (我正在寻找等效于jQuery的.trigger()方法,该方法适用于DOM事件或自定义事件。)

If you are looking for equivalent of trigger in yui3 you can try using the 'simulate' 如果您在yui3中寻找触发器的等效项,则可以尝试使用“模拟”

Y.one('button selector').simulate('click');

For the above statement to work you will need to add "node-event-simulate" roll up in the use method. 为了使上面的语句起作用,您将需要在use方法中添加“ node-event-simulate”汇总。

Do you really need to trigger the click event on the button? 您是否真的需要触发按钮上的click事件? Take the HTML below 采取以下HTML

    <button id="myButton">Click Me</button>
<br>
    <a href="#">Click Me</a>

You can make use of the custom events to put the real logic somewhere central. 您可以利用自定义事件将真实的逻辑放在中心位置。

YUI().use("node","event",function(Y){
    Y.one("#myButton").on("click",function(){Y.fire("custom:doThing")});
    Y.all("a").on("click",function(){Y.fire("custom:doThing")});
    Y.on("custom:doThing",function(){console.log("Do my thing, regardless of event source")})
});

Fiddle: http://jsfiddle.net/WZZmR/ 小提琴: http//jsfiddle.net/WZZmR/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM