项目作者: nj-coder

项目描述 :
ID based simple and light-weight (1KB) event emitter library for JavaScript.
高级语言: JavaScript
项目地址: git://github.com/nj-coder/nj-events.git
创建时间: 2019-11-16T23:59:43Z
项目社区:https://github.com/nj-coder/nj-events

开源协议:MIT License

下载


NJ-Events

Simple and light-weight event emitter library for JavaScript.

  • No dependencies, less than 1KB pure JavaScript implementation.
  • on method returns an ID. Use this ID to remove specific listener or the event-name to remove all the listeners.
  • No aliases, just emit, on and off methods.
  1. const emitter = new NJEvents();
  2. const id = emitter.on('hey', data => {
  3. console.log(data);
  4. });
  5. emitter.emit('hey', 'how are you?');
  6. emitter.off(id);

Installation

  1. npm install --save nj-events

You can use NJEvents as an ES6 module as follows:

  1. import NJEvents from 'nj-events';
  2. const emitter = new NJEvents();

Alertnatively you can include the script.js script before the closing </body> tag and then in your JS create a new instance of NJEvents as below.

  1. <script src="path/to/script.js"></script>
  2. <script>
  3. const emitter = new NJEvents();
  4. </script>

Usage

NJ-Events are driven by the on, emit, off methods which are detailed below.

Registering an event

  • on() - the listener is registered and will be active until removed explicitly.
  • once() - the listener is removed after first trigger.
  • both methods take an event_name:string, callback:function and an optional id:string as parameters.
    ```js
    const emitter = new NJEvents();

const id_on = emitter.on(‘hey’, data => { // listener is registered until removed
console.log(data);
});

const id_once = emitter.once(‘hey’, data => { // listener is removed after first trigger
console.log(data);
});

const custom_id = emitter.on(‘hey’, data => { // init with custom id
console.log(data);
}, YOUR_CUSTOM_ID);

  1. ### Triggering an event
  2. An event is triggered using the `emit()` by passing the `event_name:string` and `data:any`
  3. ```js
  4. emitter.emit('hey', 'how are you?');

Unregistering an event

An event can be unregistered using the off() with the below parameters

  • event_name - any matching events and its listeners will be removed.
  • id - event with the particular id will be removed, the event would still exist.
    1. emitter.off('hey'); // unregister using event-name
    2. emitter.off(id); // unregister using the event ID

    Releases and Changes

    Check out the Releases and Change Logs for more information.

The MIT license