简体   繁体   English

在 jQuery 中简洁地添加自定义事件触发器

[英]Succinctly Adding Custom Event Triggers in jQuery

I have a rather large and convoluted JavaScript module that is used on multiple pages of my site.我有一个相当大且复杂的 JavaScript 模块,用于我网站的多个页面。 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.我遇到的一个问题是,当我期望这个事件只触发一次时,它会快速连续触发 2-4 次。 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?另外,如何在不引用某些 DOM 对象的情况下将函数附加到事件? Simply using $.on() doesn't work.简单地使用$.on()是行不通的。

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.我可能弄错了,但我很确定 $.trigger() 不会像你使用它那样工作。 It has to be attached to a jQuery object eg.它必须附加到一个 jQuery 对象,例如。 $().trigger() . $().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() .对于你的第二个问题......你不必完全使用 DOM 元素,但你可以使用像$({}).on()这样的空 jquery 对象。 See this fiddle .看到这个小提琴

Hope this helps some.希望这会有所帮助。

On a side note, you may be confusing jQuery object methods with core methods.附带说明一下,您可能会将 jQuery 对象方法与核心方法混淆。 here is a little info just in case.这里有一些信息以防万一。

Use利用

$('#some-element').trigger('custom_event');

instead of代替

$.trigger('custom_event');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM