繁体   English   中英

当我的函数完成时,使用javascript(或jquery)触发自定义事件

[英]Fire a custom event with javascript (or jquery) when my function finishes

我没有在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/

暂无
暂无

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

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