YUI3: How would I trigger an event?

流过昼夜 提交于 2019-12-13 21:27:15

问题


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. If I am supposed to use fire(), then will myButton.fire('click') work?

(I'm looking for the equivalent of jQuery's .trigger() method, which works on DOM events or custom events.)


回答1:


Do you really need to trigger the click event on the button? Take the HTML below

    <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/




回答2:


If you are looking for equivalent of trigger in yui3 you can try using the 'simulate'

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.



来源:https://stackoverflow.com/questions/19363280/yui3-how-would-i-trigger-an-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!