gpt4 book ai didi

javascript - 当我的函数完成时,使用 JavaScript(或 jQuery)触发自定义事件

转载 作者:数据小太阳 更新时间:2023-10-29 04:29:12 24 4
gpt4 key购买 nike

我不想在 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');

Gratuitous live example | source

或者为了完全脱离 DOM,有几个发布/订阅 jQuery 插件,like this one .

关于javascript - 当我的函数完成时,使用 JavaScript(或 jQuery)触发自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11164789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com