【问题标题】:Fire a custom event with JavaScript (or jQuery) when my function finishes当我的函数完成时,使用 JavaScript(或 jQuery)触发自定义事件
【发布时间】:2022-02-01 20:22:42
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery node.js events eventemitter


    【解决方案1】:

    好吧,您可以在一些常见元素上使用自定义事件,例如 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

    【讨论】:

      【解决方案2】:
      $('#foo').on('custom', function(event, param1, param2) {
        alert(param1 + "\n" + param2);
      });
      $('#foo').trigger('custom', ['Custom', 'Event']);
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-08
        • 2017-11-11
        • 1970-01-01
        • 2013-05-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多