我想知道如何将自定义事件添加到类的实例并为该实例调用它。
我现在的代码:
var event = document.createEvent('event');
event.initEvent('build', true, true);
class link {
constructor(Href, Text = "Click me", Target = "__blank") {
this.href = Href;
this.text = Text
this.target = Target;
this.eventElm = document.createElement("event");
//this.event = document.createEvent('event');
//this.event.initEvent('build', true, true);
}
}
class creator {
constructor(Objs) {
for(var i in Objs) {
window.document.body.innerHTML += "<a href="+Objs[i].href+">"+Objs[i].text+"</a><br>";
if(Objs[i].href == "#") {
Objs[i].eventElm.dispatchEvent(event);
}
}
}
}
var l = new link("#");
var lo = new link("#");
var ar = [];
ar.push(l);
ar.push(lo);
l.eventElm.addEventListener('build', function(e) {
console.log(e);
}, false);
//l.eventElm.dispatchEvent(event);
window.onload = function () {
var crea = new creator(ar);
console.log(l.href);
}
此代码返回错误
eventtest.html:24 Uncaught DOMException: Failed to execute 'dispatchEvent' on 'EventTarget': The event is already being dispatched. at new creator (http://localhost/eventtest.html:24:25) at window.onload (http://localhost/eventtest.html:44:16)
我想在没有 jquery 的普通 javascript 中执行此操作。感谢您花时间阅读本文并希望对我有所帮助。
最佳答案
您正在声明一个全局 event
变量。但是大多数浏览器(IE、Edge、Chrome)已经有一个全局的event
变量(currently-being-dispatched event)。因此,您最终尝试重新调度正在处理的 load
事件。
这是不将代码放在全局范围内的众多原因之一。相反,将其包装在一个作用域函数中:
(function() {
// Your code here...
})();
现在,您的 event
变量不会与全局 event
冲突。
实例:
(function() {
var event = document.createEvent('event');
event.initEvent('build', true, true);
class link {
constructor(Href, Text = "Click me", Target = "__blank") {
this.href = Href;
this.text = Text
this.target = Target;
this.eventElm = document.createElement("event");
//this.event = document.createEvent('event');
//this.event.initEvent('build', true, true);
}
}
class creator {
constructor(Objs) {
for(var i in Objs) {
window.document.body.innerHTML += "<a href="+Objs[i].href+">"+Objs[i].text+"</a><br>";
if(Objs[i].href == "#") {
Objs[i].eventElm.dispatchEvent(event);
}
}
}
}
var l = new link("#");
var lo = new link("#");
var ar = [];
ar.push(l);
ar.push(lo);
l.eventElm.addEventListener('build', function(e) {
console.log(e);
}, false);
//l.eventElm.dispatchEvent(event);
window.onload = function () {
var crea = new creator(ar);
console.log(l.href);
}
})();
另外:您可能希望在每次分派(dispatch)事件时都创建一个新的事件对象,而不是拥有一个全局到您的代码的 event
变量。
关于Javascript 类和自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47052493/