Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当我的函数完成时,使用javascript(或jquery)触发自定义事件_Javascript_Jquery_Events_Node.js_Javascript Events - Fatal编程技术网

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

当我的函数完成时,使用javascript(或jquery)触发自定义事件,javascript,jquery,events,node.js,javascript-events,Javascript,Jquery,Events,Node.js,Javascript Events,我不想在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

我不想在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']);