简体   繁体   English

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

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

Instead of having nested callbacks in JS, I would like to fire and listen to my own custom events. 我没有在JS中嵌套回调,而是想开火并听我自己的自定义事件。 I don't need or want to access the DOM. 我不需要或不想访问DOM。 Here's an example: 这是一个例子:

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");
});

Would it be possible to do that with normal javascript code or with a library like jQuery? 是否可以使用普通的javascript代码或像jQuery这样的库来实现? If not, what's a good approach to avoid nested callbacks? 如果没有,那么避免嵌套回调的好方法是什么?

Thanks! 谢谢!

Well, you can use custom events on some common element, say document.body . 好吧,你可以在一些常见的元素上使用自定义事件,比如document.body

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

// Publish
$(document.body).trigger('nifty.event');

Gratuitous live example | 无偿的现场例子 | source 资源

Or for complete disconnection from the DOM, there are a couple of pub/sub jQuery plug-ins, like this one . 或者为了完全断开与DOM的连接,有一些pub / sub jQuery插件, 就像这个插件一样

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

Source: http://api.jquery.com/trigger/ 资料来源: http//api.jquery.com/trigger/

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

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