var iSubmit = {
addEventListener: document.addEventListener || document.attachEvent,
dispatchEvent: document.dispatchEvent,
fireEvent: document.fireEvent,
//the method below is added for completeness, but is not causing the problem.
test: function(memo) {
var name = "test";
var event;
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent(name, true, true);
} else {
event = document.createEventObject();
event.eventType = name;
}
event.eventName = name;
event.memo = memo || { };
if (document.createEvent) {
try {
document.dispatchEvent(event);
} catch (ex) {
iAlert.debug(ex, 'iPushError');
}
} else {
document.fireEvent("on" + event.eventType, event);
}
}
}
iSubmit.addEventListener("test", function(e) { console.log(e); }, false);
//This call is added to have a complete test. The errors are already triggered with the line before this one.
iSubmit.test();
这将返回一个错误:添加事件监听器失败:TypeError:在不实现EventTarget接口的对象上调用 'addEventListener'
现在,这段代码将被用于一个PhoneGap应用程序中,在Android / iOS上可以工作。然而,在测试期间,如果我至少能让它在一个浏览器中工作,那就太好了。
PS> 我知道我可以启用冒泡,然后监听文档根,但我想有一点面向对象编程,使每个对象都能独立工作。
var emitter = require('events').EventEmitter;
的事情。但是我们能在普通的JS中像这样做吗?ourObject.prototype.__proto__ = EventTarget.prototype;
? - Siva Tumma