【发布时间】:2021-10-03 15:09:25
【问题描述】:
来自 c# 背景,我只想在我的代码的某个点创建一个事件,以便在 elsewere 中调度,这意味着如果在代码的某些部分有订阅,则调用此委托函数.
所以我尝试这样做:
function myFunction() {
console.log("delegated call achieved!");
}
const myEvent = new Event('onMyConditionIsMet', myFunction, false);
//at this point the program the subscription takes place
function whatever1() {
//...not meaningfull code
myEvent.addEventListener('onMyConditionIsMet');
//myEvent += myFunction; c# way subscription in case it makes sense
}
//at this point in the program, event subscription is checked and
//delegate func run in case there has been a subscription
function whatever2() {
//...not meaningfull code
myEvent?.invoke(); // ?.invoke(); would be the c# way to do it.
}
我发现的所有示例都与 DOM 事件有关,但我的情况是针对我自己创建的事件,认为这些被称为合成事件。 我在这个问题中做出的另一个假设是委托调用函数中没有参数,因此,为了明确命名,它将是一个没有参数的委托。只是指出这一点,因为在 c# 中事件只是没有参数的委托函数,因此是一种特定类型的委托。不确定这在 JavaScript 中是否同样有效。
这样做的方法是什么? (意思是创建一个简单的事件实例,订阅,如果有订阅则执行委托代码)?
【问题讨论】:
-
找Document.createEvent(),例子很清楚。
-
感谢您的评论,检查。文档中的
elem是什么?在elem.addEventListener('build', function (e) { // e.target matches elem }, false); -
应用它的 DOM 元素。
-
在我的情况下没有 dom 元素,这就是我的困惑来自
-
如果问题出在没有dom的node.js中,或者事件与任何DOM元素无关,那么创建事件、订阅和委托执行代码的方式是什么?.这就是我的问题的重点
标签: javascript events delegates