[英]jQuery trigger() with Custom Event?
I'm working with some code (written by someone else) that is something like the following: 我正在使用一些代码(由其他人编写),如下所示:
var _layoutRoot = $("#whatever");
eventName = 'CopyArticle';
eventData = { targetArticleIds: selectedArticleIds, targetCategoryIds: selectedCategoryIds };
// fire the event
if (eventName) // null is unexepcted here
_layoutRoot.trigger(eventName, eventData);
I just don't know enough about what this means. 我只是不清楚这意味着什么。
I can see that trigger
causes the named event to happen. 我可以看到trigger
导致命名事件发生。 But since when is there a JavaScript CopyArticle
event? 但是,什么时候有一个JavaScript CopyArticle
事件? How is this a valid event and how would it be handled? 这是一个有效的事件,它将如何处理?
jQuery allows you to fire an event of any name you want jQuery允许您触发任何名称的事件
$(".foo").on("some:custom:event", function(event) {
console.log("hello");
});
$(".foo").trigger("some:custom:event");
// hello
Just attach your custom event to an element with on
. 只需将自定义事件附加到on
的元素即可。 To fire the event use trigger
. 要触发事件,请使用trigger
。 You can pass extra arguments to the trigger function using an array. 您可以使用数组将额外参数传递给触发器函数。
HTML HTML
<div id="test"></div>
JS JS
$("#test").on("customEvent", function(e,msg){
alert(msg);
});
var dataToPass = "This is a msg";
$("#test").trigger("customEvent", [dataToPass]);
JS Fiddle: http://jsfiddle.net/85wjt/1/ JS小提琴: http : //jsfiddle.net/85wjt/1/
As per the jquery website 根据jquery 网站
When we define a custom event type using the .on() method, the second argument to .trigger() can become useful. 当我们使用.on()方法定义自定义事件类型时,.trigger()的第二个参数可能会变得有用。 For example, suppose we have bound a handler for the custom event to our element instead of the built-in click event as we did above: 例如,假设我们已将自定义事件的处理程序绑定到我们的元素而不是上面的内置click事件:
$( "#foo" ).on( "custom", function( event, param1, param2 ) {
alert( param1 + "\n" + param2 );
});
$( "#foo").trigger( "custom", [ "Custom", "Event" ] );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.