gpt4 book ai didi

javascript - 触发隐藏在函数内但绑定(bind)到 'window' 的自定义事件

转载 作者:行者123 更新时间:2023-11-27 22:36:54 28 4
gpt4 key购买 nike

我认为我可以通过执行 window.dispatchEvent(test) 来调度 test 事件。事实上,如果我将事件监听器从 test 更改为 click,它就会触发警报。

我做错了什么?

var functionName = function () {
function functionName() {

// bind method
this.doSomething = this.doSomething.bind(this);

this.setupListeners();
}

functionName.prototype.setupListeners = function setupListeners() {
window.addEventListener('test', this.doSomething);
};

functionName.prototype.doSomething = function doSomething(event) {
alert('Hello!');
};

return functionName;

}();

最佳答案

您必须像这样创建事件对象:

var event = new Event('test');

// Dispatch the event.
window.dispatchEvent(event);

查看工作片段:

var functionName = function() {
function functionName() {

// bind method
this.doSomething = this.doSomething.bind(this);

this.setupListeners();
}

functionName.prototype.setupListeners = function setupListeners() {
window.addEventListener('test', this.doSomething);
};

functionName.prototype.doSomething = function doSomething(event) {
alert('Hello!');
};

return functionName;

}();

var myfun = new functionName();

var event = new Event('test');

// Dispatch the event.
window.dispatchEvent(event);

关于javascript - 触发隐藏在函数内但绑定(bind)到 'window' 的自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39031543/

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