是否可以创建一个可以像 HTMLElements 一样分派事件的对象并将其用作我的新类的原型?
我知道我可以编写一个 EventDispatcher 类来为我做这个,但我相信它比使用已经这样做的本机函数(addEventListener、removeEventListener、dispatchEvent)要慢。
情况1:
var obj = new EventDispatcher();
obj.addEventListener( 'someevent', listener ); // obj can receive listener to a event
obj.dispatchEvent( myEvent ); // CustomEvent being dispatched
案例二:
var MyNewClass = function(){};
// MyNewClass now can dispatch events in their instances...
MyNewClass.prototype = Object.create( EventDispatcher.prototype );
var obj2 = new MyNewClass();
obj2.addEventListener( 'someevent', listener ); // works!