最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery trigger() with Custom Event? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Dec 18, 2013 at 1:25 Jonathan WoodJonathan Wood 67.2k82 gold badges300 silver badges526 bronze badges 1
  • jQuery allows custom events. – Derek 朕會功夫 Commented Dec 18, 2013 at 1:26
Add a comment  | 

3 Answers 3

Reset to default 10

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" ] );

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
发布评论

评论列表(0)

  1. 暂无评论