当我的函数完成时,使用 JavaScript(或 jQuery)触发一个自定义事件

Fire a custom event with JavaScript (or jQuery) when my function finishes

本文关键字:事件 自定义 一个 完成时 函数 我的 使用 JavaScript jQuery      更新时间:2023-09-26

我想触发并侦听我自己的自定义事件,而不是在JS中嵌套回调。我不需要也不想访问 DOM。下面是一个示例:

function doSomething(){
//...
$.trigger('finished-doSomething'); //fire the event 'finished-doSomething'
}
//when the event 'finished-doSomething' is fired -> execute the function in the second  param 
$.live('finished-doSomething', function(){
   alert("I finished-doSomething");
});
是否可以

使用普通的JavaScript代码或像jQuery这样的库来做到这一点?如果没有,避免嵌套回调的好方法是什么?

好吧,您可以在一些常见元素上使用自定义事件,例如document.body

// Subscribe
$(document.body).on('nifty.event', function() {
    // Handle it
});
// Publish
$(document.body).trigger('nifty.event');

无偿现场示例 | 来源

或者为了完全断开与DOM的连接,有几个pub/sub jQuery插件,就像这个一样。

$('#foo').on('custom', function(event, param1, param2) {
  alert(param1 + "'n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);

来源: http://api.jquery.com/trigger/