简体   繁体   中英

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. But since when is there a JavaScript CopyArticle event? How is this a valid event and how would it be handled?

jQuery allows you to fire an event of any name you want

$(".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 . To fire the event use trigger . You can pass extra arguments to the trigger function using an array.

HTML

<div id="test"></div>

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/

As per the jquery website

When we define a custom event type using the .on() method, the second argument to .trigger() can become useful. 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:

$( "#foo" ).on( "custom", function( event, param1, param2 ) {
  alert( param1 + "\n" + param2 );
});
$( "#foo").trigger( "custom", [ "Custom", "Event" ] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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