7

我不想在 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 这样的库来做到这一点?如果不是,那么避免嵌套回调的好方法是什么?

4

2 回答 2

15

好吧,您可以在某些常见元素上使用自定义事件,例如document.body.

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

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

无偿的活生生的例子| 来源

或者为了与 DOM 完全断开连接,有几个 pub/sub jQuery 插件,比如这个.

于 2012-06-22T22:13:53.800 回答
0
$('#foo').on('custom', function(event, param1, param2) {
  alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);

来源:http ://api.jquery.com/trigger/

于 2013-05-02T22:57:10.630 回答