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?
- jQuery allows custom events. – Derek 朕會功夫 Commented Dec 18, 2013 at 1:26
3 Answers
Reset to default 10Just 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