EventTarget-constructible.any.js (1971B)
1 "use strict"; 2 3 test(() => { 4 const target = new EventTarget(); 5 const event = new Event("foo", { bubbles: true, cancelable: false }); 6 let callCount = 0; 7 8 function listener(e) { 9 assert_equals(e, event); 10 ++callCount; 11 } 12 13 target.addEventListener("foo", listener); 14 15 target.dispatchEvent(event); 16 assert_equals(callCount, 1); 17 18 target.dispatchEvent(event); 19 assert_equals(callCount, 2); 20 21 target.removeEventListener("foo", listener); 22 target.dispatchEvent(event); 23 assert_equals(callCount, 2); 24 }, "A constructed EventTarget can be used as expected"); 25 26 test(() => { 27 const target = new EventTarget(); 28 const event = new Event("foo"); 29 30 function listener(e) { 31 assert_equals(e, event); 32 assert_equals(e.target, target); 33 assert_equals(e.currentTarget, target); 34 assert_array_equals(e.composedPath(), [target]); 35 } 36 target.addEventListener("foo", listener, { once: true }); 37 target.dispatchEvent(event); 38 assert_equals(event.target, target); 39 assert_equals(event.currentTarget, null); 40 assert_array_equals(event.composedPath(), []); 41 }, "A constructed EventTarget implements dispatch correctly"); 42 43 test(() => { 44 class NicerEventTarget extends EventTarget { 45 on(...args) { 46 this.addEventListener(...args); 47 } 48 49 off(...args) { 50 this.removeEventListener(...args); 51 } 52 53 dispatch(type, detail) { 54 this.dispatchEvent(new CustomEvent(type, { detail })); 55 } 56 } 57 58 const target = new NicerEventTarget(); 59 const event = new Event("foo", { bubbles: true, cancelable: false }); 60 const detail = "some data"; 61 let callCount = 0; 62 63 function listener(e) { 64 assert_equals(e.detail, detail); 65 ++callCount; 66 } 67 68 target.on("foo", listener); 69 70 target.dispatch("foo", detail); 71 assert_equals(callCount, 1); 72 73 target.dispatch("foo", detail); 74 assert_equals(callCount, 2); 75 76 target.off("foo", listener); 77 target.dispatch("foo", detail); 78 assert_equals(callCount, 2); 79 }, "EventTarget can be subclassed");