2012-06-22 33 views
7

而不是在JS中嵌套回調,我想觸發並聆聽我自己的自定義事件。我不需要或不想訪問DOM。這裏有一個例子:當我的函數完成時用javascript(或jquery)觸發自定義事件

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一樣的庫嗎?如果不是,避免嵌套回調的好方法是什麼?

謝謝!

回答

15

那麼,你可以在一些常見的元素上使用自定義事件,比如document.body

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

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

Gratuitous live example | source

或者爲了完全斷開DOM,有幾個pub/sub jQuery插件,like this one

0
$('#foo').on('custom', function(event, param1, param2) { 
    alert(param1 + "\n" + param2); 
}); 
$('#foo').trigger('custom', ['Custom', 'Event']); 

來源:​​

相關問題