当我的功能完成时,使用javascript(或jquery)触发自定义事件 [英] Fire a custom event with javascript (or jquery) when my function finishes

查看:102
本文介绍了当我的功能完成时,使用javascript(或jquery)触发自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想在JS中嵌套回调,而是要触发并听我自己的自定义事件。我不需要或想要访问DOM。这里有一个例子:

Instead of having nested callbacks in JS, I would like to fire and listen to my own custom events. I don't need or want to access the 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");
});

是否可以使用正常的JavaScript代码或像jQuery这样的库这样做?如果没有,什么是避免嵌套回调的好方法?

Would it be possible to do that with normal javascript code or with a library like jQuery? If not, what's a good approach to avoid nested callbacks?

谢谢!

推荐答案

嗯,你可以在一些常见的元素上使用自定义事件,例如 document.body

Well, you can use custom events on some common element, say document.body.

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

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

免费的实例 | 来源

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

Or for complete disconnection from the DOM, there are a couple of pub/sub jQuery plug-ins, like this one.

这篇关于当我的功能完成时,使用javascript(或jquery)触发自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆