buddy

node MVC discord bot
Log | Files | Refs | README

README.md (8897B)


      1 # event-target-shim
      2 
      3 [![npm version](https://img.shields.io/npm/v/event-target-shim.svg)](https://www.npmjs.com/package/event-target-shim)
      4 [![Downloads/month](https://img.shields.io/npm/dm/event-target-shim.svg)](http://www.npmtrends.com/event-target-shim)
      5 [![Build Status](https://travis-ci.org/mysticatea/event-target-shim.svg?branch=master)](https://travis-ci.org/mysticatea/event-target-shim)
      6 [![Coverage Status](https://codecov.io/gh/mysticatea/event-target-shim/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/event-target-shim)
      7 [![Dependency Status](https://david-dm.org/mysticatea/event-target-shim.svg)](https://david-dm.org/mysticatea/event-target-shim)
      8 
      9 An implementation of [WHATWG EventTarget interface](https://dom.spec.whatwg.org/#interface-eventtarget), plus few extensions.
     10 
     11 - This provides `EventTarget` constructor that can inherit for your custom object.
     12 - This provides an utility that defines properties of attribute listeners (e.g. `obj.onclick`).
     13 
     14 ```js
     15 import {EventTarget, defineEventAttribute} from "event-target-shim"
     16 
     17 class Foo extends EventTarget {
     18     // ...
     19 }
     20 
     21 // Define `foo.onhello` property.
     22 defineEventAttribute(Foo.prototype, "hello")
     23 
     24 // Use
     25 const foo = new Foo()
     26 foo.addEventListener("hello", e => console.log("hello", e))
     27 foo.onhello = e => console.log("onhello:", e)
     28 foo.dispatchEvent(new CustomEvent("hello"))
     29 ```
     30 
     31 ## 💿 Installation
     32 
     33 Use [npm](https://www.npmjs.com/) to install then use a bundler.
     34 
     35 ```
     36 npm install event-target-shim
     37 ```
     38 
     39 Or download from [`dist` directory](./dist).
     40 
     41 - [dist/event-target-shim.mjs](dist/event-target-shim.mjs) ... ES modules version.
     42 - [dist/event-target-shim.js](dist/event-target-shim.js) ... Common JS version.
     43 - [dist/event-target-shim.umd.js](dist/event-target-shim.umd.js) ... UMD (Universal Module Definition) version. This is transpiled by [Babel](https://babeljs.io/) for IE 11.
     44 
     45 ## 📖 Usage
     46 
     47 ```js
     48 import {EventTarget, defineEventAttribute} from "event-target-shim"
     49 // or
     50 const {EventTarget, defineEventAttribute} = require("event-target-shim")
     51 
     52 // or UMD version defines a global variable:
     53 const {EventTarget, defineEventAttribute} = window.EventTargetShim
     54 ```
     55 
     56 ### EventTarget
     57 
     58 > https://dom.spec.whatwg.org/#interface-eventtarget
     59 
     60 #### eventTarget.addEventListener(type, callback, options)
     61 
     62 Register an event listener.
     63 
     64 - `type` is a string. This is the event name to register.
     65 - `callback` is a function. This is the event listener to register.
     66 - `options` is a boolean or an object `{ capture?: boolean, passive?: boolean, once?: boolean }`. If this is a boolean, it's same meaning as `{ capture: options }`.
     67     - `capture` is the flag to register the event listener for capture phase.
     68     - `passive` is the flag to ignore `event.preventDefault()` method in the event listener.
     69     - `once` is the flag to remove the event listener automatically after the first call.
     70 
     71 #### eventTarget.removeEventListener(type, callback, options)
     72 
     73 Unregister an event listener.
     74 
     75 - `type` is a string. This is the event name to unregister.
     76 - `callback` is a function. This is the event listener to unregister.
     77 - `options` is a boolean or an object `{ capture?: boolean }`. If this is a boolean, it's same meaning as `{ capture: options }`.
     78     - `capture` is the flag to register the event listener for capture phase.
     79 
     80 #### eventTarget.dispatchEvent(event)
     81 
     82 Dispatch an event.
     83 
     84 - `event` is a [Event](https://dom.spec.whatwg.org/#event) object or an object `{ type: string, [key: string]: any }`. The latter is non-standard but useful. In both cases, listeners receive the event as implementing [Event](https://dom.spec.whatwg.org/#event) interface.
     85 
     86 ### defineEventAttribute(proto, type)
     87 
     88 Define an event attribute (e.g. `onclick`) to `proto`. This is non-standard.
     89 
     90 - `proto` is an object (assuming it's a prototype object). This function defines a getter/setter pair for the event attribute.
     91 - `type` is a string. This is the event name to define.
     92 
     93 For example:
     94 
     95 ```js
     96 class AbortSignal extends EventTarget {
     97     constructor() {
     98         this.aborted = false
     99     }
    100 }
    101 // Define `onabort` property.
    102 defineEventAttribute(AbortSignal.prototype, "abort")
    103 ```
    104 
    105 ### EventTarget(types)
    106 
    107 Define a custom `EventTarget` class with event attributes. This is non-standard.
    108 
    109 - `types` is a string or an array of strings. This is the event name to define.
    110 
    111 For example:
    112 
    113 ```js
    114 // This has `onabort` property.
    115 class AbortSignal extends EventTarget("abort") {
    116     constructor() {
    117         this.aborted = false
    118     }
    119 }
    120 ```
    121 
    122 ## 📚 Examples
    123 
    124 ### ES2015 and later
    125 
    126 > https://jsfiddle.net/636vea92/
    127 
    128 ```js
    129 const {EventTarget, defineEventAttribute} = EventTargetShim
    130 
    131 // Define a derived class.
    132 class Foo extends EventTarget {
    133     // ...
    134 }
    135 
    136 // Define `foo.onhello` property.
    137 defineEventAttribute(Foo.prototype, "hello")
    138 
    139 // Register event listeners.
    140 const foo = new Foo()
    141 foo.addEventListener("hello", (e) => {
    142     console.log("hello", e)
    143 })
    144 foo.onhello = (e) => {
    145     console.log("onhello", e)
    146 }
    147 
    148 // Dispatching events
    149 foo.dispatchEvent(new CustomEvent("hello", { detail: "detail" }))
    150 ```
    151 
    152 ### Typescript
    153 
    154 ```ts
    155 import { EventTarget, defineEventAttribute } from "event-target-shim";
    156 
    157 // Define events
    158 type FooEvents = {
    159     hello: CustomEvent
    160 }
    161 type FooEventAttributes = {
    162     onhello: CustomEvent
    163 }
    164 
    165 // Define a derived class.
    166 class Foo extends EventTarget<FooEvents, FooEventAttributes> {
    167     // ...
    168 }
    169 // Define `foo.onhello` property's implementation.
    170 defineEventAttribute(Foo.prototype, "hello")
    171 
    172 // Register event listeners.
    173 const foo = new Foo()
    174 foo.addEventListener("hello", (e) => {
    175     console.log("hello", e.detail)
    176 })
    177 foo.onhello = (e) => {
    178     console.log("onhello", e.detail)
    179 }
    180 
    181 // Dispatching events
    182 foo.dispatchEvent(new CustomEvent("hello", { detail: "detail" }))
    183 ```
    184 
    185 Unfortunately, both `FooEvents` and `FooEventAttributes` are needed because TypeScript doesn't allow the mutation of string literal types. If TypeScript allowed us to compute `"onhello"` from `"hello"` in types, `FooEventAttributes` will be optional.
    186 
    187 This `EventTarget` type is compatible with `EventTarget` interface of `lib.dom.d.ts`.
    188 
    189 #### To disallow unknown events
    190 
    191 By default, methods such as `addEventListener` accept unknown events. You can disallow unknown events by the third type parameter `"strict"`.
    192 
    193 ```ts
    194 type FooEvents = {
    195     hello: CustomEvent
    196 }
    197 class Foo extends EventTarget<FooEvents, {}, "strict"> {
    198     // ...
    199 }
    200 
    201 // OK because `hello` is defined in FooEvents.
    202 foo.addEventListener("hello", (e) => {
    203 })
    204 // Error because `unknown` is not defined in FooEvents.
    205 foo.addEventListener("unknown", (e) => {
    206 })
    207 ```
    208 
    209 However, if you use `"strict"` parameter, it loses compatibility with `EventTarget` interface of `lib.dom.d.ts`.
    210 
    211 #### To infer the type of `dispatchEvent()` method
    212 
    213 TypeScript cannot infer the event type of `dispatchEvent()` method properly from the argument in most cases. You can improve this behavior with the following steps:
    214 
    215 1. Use the third type parameter `"strict"`. This prevents inferring to `dispatchEvent<string>()`.
    216 2. Make the `type` property of event definitions stricter.
    217 
    218 ```ts
    219 type FooEvents = {
    220     hello: CustomEvent & { type: "hello" }
    221     hey: Event & { type: "hey" }
    222 }
    223 class Foo extends EventTarget<FooEvents, {}, "strict"> {
    224     // ...
    225 }
    226 
    227 // Error because `detail` property is lacking.
    228 foo.dispatchEvent({ type: "hello" })
    229 ```
    230 
    231 ### ES5
    232 
    233 > https://jsfiddle.net/522zc9de/
    234 
    235 ```js
    236 // Define a derived class.
    237 function Foo() {
    238     EventTarget.call(this)
    239 }
    240 Foo.prototype = Object.create(EventTarget.prototype, {
    241     constructor: { value: Foo, configurable: true, writable: true }
    242     // ...
    243 })
    244 
    245 // Define `foo.onhello` property.
    246 defineEventAttribute(Foo.prototype, "hello")
    247 
    248 // Register event listeners.
    249 var foo = new Foo()
    250 foo.addEventListener("hello", function(e) {
    251     console.log("hello", e)
    252 })
    253 foo.onhello = function(e) {
    254     console.log("onhello", e)
    255 }
    256 
    257 // Dispatching events
    258 function isSupportEventConstrucor() { // IE does not support.
    259     try {
    260         new CusomEvent("hello")
    261         return true
    262     } catch (_err) {
    263         return false
    264     }
    265 }
    266 if (isSupportEventConstrucor()) {
    267     foo.dispatchEvent(new CustomEvent("hello", { detail: "detail" }))
    268 } else {
    269     var e = document.createEvent("CustomEvent")
    270     e.initCustomEvent("hello", false, false, "detail")
    271     foo.dispatchEvent(e)
    272 }
    273 ```
    274 
    275 ## 📰 Changelog
    276 
    277 - See [GitHub releases](https://github.com/mysticatea/event-target-shim/releases).
    278 
    279 ## 🍻 Contributing
    280 
    281 Contributing is welcome ❤️
    282 
    283 Please use GitHub issues/PRs.
    284 
    285 ### Development tools
    286 
    287 - `npm install` installs dependencies for development.
    288 - `npm test` runs tests and measures code coverage.
    289 - `npm run clean` removes temporary files of tests.
    290 - `npm run coverage` opens code coverage of the previous test with your default browser.
    291 - `npm run lint` runs ESLint.
    292 - `npm run build` generates `dist` codes.
    293 - `npm run watch` runs tests on each file change.