Avoid search prototype chain (#2019)

This commit is contained in:
迷渡 2019-03-30 20:18:19 +08:00 committed by Ryan Dahl
parent 3d6c033369
commit 51c6f33f64
2 changed files with 26 additions and 3 deletions

View file

@ -14,7 +14,7 @@ export class EventTarget implements domTypes.EventTarget {
listener: domTypes.EventListenerOrEventListenerObject | null, listener: domTypes.EventListenerOrEventListenerObject | null,
_options?: boolean | domTypes.AddEventListenerOptions _options?: boolean | domTypes.AddEventListenerOptions
): void { ): void {
if (!(type in this.listeners)) { if (!this.listeners.hasOwnProperty(type)) {
this.listeners[type] = []; this.listeners[type] = [];
} }
if (listener !== null) { if (listener !== null) {
@ -27,7 +27,7 @@ export class EventTarget implements domTypes.EventTarget {
callback: domTypes.EventListenerOrEventListenerObject | null, callback: domTypes.EventListenerOrEventListenerObject | null,
_options?: domTypes.EventListenerOptions | boolean _options?: domTypes.EventListenerOptions | boolean
): void { ): void {
if (type in this.listeners && callback !== null) { if (this.listeners.hasOwnProperty(type) && callback !== null) {
this.listeners[type] = this.listeners[type].filter( this.listeners[type] = this.listeners[type].filter(
listener => listener !== callback listener => listener !== callback
); );
@ -35,7 +35,7 @@ export class EventTarget implements domTypes.EventTarget {
} }
public dispatchEvent(event: domTypes.Event): boolean { public dispatchEvent(event: domTypes.Event): boolean {
if (!(event.type in this.listeners)) { if (!this.listeners.hasOwnProperty(event.type)) {
return true; return true;
} }
const stack = this.listeners[event.type].slice(); const stack = this.listeners[event.type].slice();

View file

@ -64,3 +64,26 @@ test(function removingNullEventListenerShouldSucceed() {
assertEquals(document.removeEventListener("x", null, true), undefined); assertEquals(document.removeEventListener("x", null, true), undefined);
assertEquals(document.removeEventListener("x", null), undefined); assertEquals(document.removeEventListener("x", null), undefined);
}); });
test(function constructedEventTargetUseObjectPrototype() {
const target = new EventTarget();
const event = new Event("toString", { bubbles: true, cancelable: false });
let callCount = 0;
function listener(e): void {
assertEquals(e, event);
++callCount;
}
target.addEventListener("toString", listener);
target.dispatchEvent(event);
assertEquals(callCount, 1);
target.dispatchEvent(event);
assertEquals(callCount, 2);
target.removeEventListener("toString", listener);
target.dispatchEvent(event);
assertEquals(callCount, 2);
});