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

cna*_*reu 7 javascript jquery events javascript-events node.js

我没有在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");
});
Run Code Online (Sandbox Code Playgroud)

是否可以使用普通的javascript代码或像jQuery这样的库来实现?如果没有,那么避免嵌套回调的好方法是什么?

谢谢!

T.J*_*der 15

那么,你可以在一些常见元素上使用自定义事件document.body.

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

// Publish
$(document.body).trigger('nifty.event');
Run Code Online (Sandbox Code Playgroud)

无偿的现场例子 | 资源

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