我认为我可以通过执行 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/