summaryrefslogtreecommitdiffstats
path: root/testing/web-platform/tests/dom/events/EventTarget-constructible.any.js
blob: b0e7614e625b3de018eb76c90148c7710b6c807f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"use strict";

test(() => {
  const target = new EventTarget();
  const event = new Event("foo", { bubbles: true, cancelable: false });
  let callCount = 0;

  function listener(e) {
    assert_equals(e, event);
    ++callCount;
  }

  target.addEventListener("foo", listener);

  target.dispatchEvent(event);
  assert_equals(callCount, 1);

  target.dispatchEvent(event);
  assert_equals(callCount, 2);

  target.removeEventListener("foo", listener);
  target.dispatchEvent(event);
  assert_equals(callCount, 2);
}, "A constructed EventTarget can be used as expected");

test(() => {
  class NicerEventTarget extends EventTarget {
    on(...args) {
      this.addEventListener(...args);
    }

    off(...args) {
      this.removeEventListener(...args);
    }

    dispatch(type, detail) {
      this.dispatchEvent(new CustomEvent(type, { detail }));
    }
  }

  const target = new NicerEventTarget();
  const event = new Event("foo", { bubbles: true, cancelable: false });
  const detail = "some data";
  let callCount = 0;

  function listener(e) {
    assert_equals(e.detail, detail);
    ++callCount;
  }

  target.on("foo", listener);

  target.dispatch("foo", detail);
  assert_equals(callCount, 1);

  target.dispatch("foo", detail);
  assert_equals(callCount, 2);

  target.off("foo", listener);
  target.dispatch("foo", detail);
  assert_equals(callCount, 2);
}, "EventTarget can be subclassed");