I have a rather large and convoluted JavaScript module that is used on multiple pages of my site. After a bit of searching and fiddling, I came up with the following structure to run some extra code when one of the module’s functions run on a specific page.
// within module definition that is used across multiple pages
function some_module_method(){
$.event.trigger( 'custom_event' );
}
// bit of functionality that I'm trying to add to a single page
$( '#some-element' ).on( 'custom_event', function(){
console.log( 'The custom event has just been triggered!' );
} );
One problem I’m having is that when I’m expecting this event to only trigger once, it will go off 2-4 times in quick succession. Is this a problem with the structure above that I’m using to trigger and attach this event, or probably something else?
Also, how can I attach a function to an event without referencing some DOM object? Simply using $.on() doesn’t work.
For your first issue, it’s a little hard to say without seeing an example. And I could be mistaken, but I’m pretty sure $.trigger() will not work like you’re using it. It has to be attached to a jQuery object e.g..
$().trigger().And for your second question… You don’t have to use a DOM element exactly, but you can use an empty jquery object like
$({}).on(). See this fiddle.Hope this helps some.
On a side note, you may be confusing jQuery object methods with core methods. here is a little info just in case.