Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch the jQuery.event.trigger()?

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

like image 988
Moszeed Avatar asked Jun 21 '12 06:06

Moszeed


People also ask

What triggered the event in jQuery?

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.

How do you check event is triggered or not in jQuery?

$('button'). click(function(event, wasTriggered) { if (wasTriggered) { alert('triggered in code'); } else { alert('triggered by mouse'); } }); $('button').

What is trigger (' click ')?

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.

How do you check if an event has been triggered in JavaScript?

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.


2 Answers

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
like image 136
raina77ow Avatar answered Oct 18 '22 02:10

raina77ow


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' }]);
like image 7
Judah Anthony Avatar answered Oct 18 '22 03:10

Judah Anthony