【发布时间】:2020-08-25 13:46:27
【问题描述】:
我在addEventListener.call(ob) 上收到非法调用错误。这是我的示例代码:
function MyClass(name) {
var target = document.createTextNode(null);
this.addEventListener = target.addEventListener.bind(target);
this.removeEventListener = target.removeEventListener.bind(target);
this.dispatchEvent = target.dispatchEvent.bind(target);
this.MyName = name;
this.ModifyName = function(newName) {
this.MyName = newName;
this.dispatchEvent(new Event("Change"));
};
}
MyClass.prototype = EventTarget.prototype;
function changeHandler() {
console.log(`From changeHandler`);
}
function changeHandler2() {
console.log(`From changeHandler2`);
}
function test() {
var ob = new MyClass("OrgName");
ob.addEventListener("Change", changeHandler);
addEventListener.call(ob, "Change", function() { changeHandler() }); // <-- Illegal invocation
console.log(ob.MyName);
ob.ModifyName("UpdatedName");
console.log(ob.MyName);
}
test();
更新
我实际上已经为 XmlHttpRequest 创建了代理类,它拦截所有的 ajax 请求/响应。它工作正常,直到 angular 开始使用 addEventListener.call(xhr, "readystatechange", callback)。在这里,xhr 是我的代理类的对象。我对角码没有任何控制权。我只能修改我的代理类。我可以通过上面的示例代码重现“非法调用”错误。所以上面的示例代码就像我的场景的模拟器。
有什么建议吗?
【问题讨论】:
-
您不能将事件侦听器添加到文本节点。将文本包裹在一个跨度或其他东西中。
-
你也不能在课堂上调用它。
addEventListener属于 DOM 元素。
标签: javascript events dom-events addeventlistener