i want to build a custom event with jQuery that is not set to a DOM element.
It says in the jQuery description, that:
jQuery.event.trigger('test');
is to trigger an Custom Event.
But how i can catch it ??
thx in advance
jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.
$('button'). click(function(event, wasTriggered) { if (wasTriggered) { alert('triggered in code'); } else { alert('triggered by mouse'); } }); $('button').
trigger( "click" ); As of jQuery 1.3, . trigger() ed events bubble up the DOM tree; an event handler can stop the bubbling by returning false from the handler or calling the . stopPropagation() method on the event object passed into the event.
To check if event is triggered by a human with JavaScript, we can use the isTrusted property. to check if the event is triggered by a human in our event handler callback. e is the event object and it had the isTrusted property. If isTrusted is true , then the event is triggered by a human.
I suppose you're asking about that custom event (at least it made no sense for me attempting to catch the trigger
): it's done with .bind:
$('some_selector').bind('test', function() {
console.log('Test was caught'); }
);
UPDATE: Actually no, you don't need a selector - just an object to be a 'host' of event. You might use something like this:
// taken from the comments at the Doc page
var o = {length: 3};
$(o).bind( 'custom', function(){ console.log('hi') } );
$(o).trigger('custom');
// Output
hi
hi
hi
I think you guys are missing the question. He is not asking how you listen for an event triggered on an object. He is asking how you listen for an event triggered directly through jQuery.event.trigger().
I found a really great article at http://www.sitepoint.com/jquery-custom-events/.
Essentially you just listen on the document object.
$(document).on("test", function(event, data) {
console.log(data)
});
$.event.trigger('test', [{ foo: 'bar' }]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With