event-emit
Dependency free lightweight implementation of Observer pattern in Javascript
Features
- Dependency free
- Cross-browser: Chrome, Safari 3+, FF 1.5+, IE 5.5+, Opera 7+, all mobile browsers
- Supports a context for subscribers
- Supports subscribing to multiple events at once
- Simple: no bullshit like namespaces, async event emitting, priority, try/catch etc
- Small size: (750 bytes minified and gzipped)
- Provided as a UMD module
Install
Install it from NPM:
npm install event-emit
Or download it directly from /dist/event-emit.min.js
Usage
Include it as a script tag to your HTML page:
Or use it as a CommonJS module:
var EventEmit =
or as a AMD module:
;
or as a ES2015 module:
Examples
Basic example
const componentA = {} EventEmit // Subscribe to eventcomponentA; // Publish the eventcomponentA;
Listener context
const componentA = {}const componentB = { console // true } EventEmit // Subscribe to the event and pass a context for the listenercomponentA;
Pass data to the listener
const componentA = {} EventEmit componentA; // Publish the eventcomponentA;
Add a one time subscription
const componentA = {} EventEmit // Subscribe to the eventcomponentA; componentA; // "event fired"componentA; // Nothing happened
Remove a subscription
const componentA = {}const componentB = {} EventEmit // Define a listener {} // Subscribe to eventscomponentAcomponentAcomponentAcomponentA // Publish the eventcomponentA // Remove the first subscription that was created w/o contextcomponentA // Remove the second subscription w/ contextcomponentA // Remove all listeners of given eventcomponentA
Deal with a list of events
const componentA = {} EventEmit // Defined a listener { console} // Add this listener for three events at oncecomponentA // Publish two eventscomponentA // remove specific listener of event_1 and event_2componentA // remove all subscriptions of event_2 and event_3componentA
PubSub pattern implementation
const emit: publish on: subscribe off: unsubscribe } = EventEmitprototype; publish subscribe unsubscribe
// component-a/index.js pubsub
// component-b/index.js pubsub
License
MIT