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

而不是在JS中嵌套callback,我想开火,听我自己的自定义事件。 我不需要或不想访问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的库? 如果没有,避免嵌套callback的好方法是什么?

谢谢!

那么,你可以在一些常见的元素上使用自定义事件,比如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/