当我的函数完成时,使用javascript(或jquery)触发自定义事件
我不想在JS中嵌套回调,而是想触发并监听我自己的自定义事件。我不需要或不想访问DOM。下面是一个例子:当我的函数完成时,使用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
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']);