簡體   English   中英

當我的函數完成時,使用javascript(或jquery)觸發自定義事件

[英]Fire a custom event with javascript (or jquery) when my function finishes

我沒有在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']);

資料來源: http//api.jquery.com/trigger/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM