Mitty
Simple event emitter for javascript. Enables objects to publish and subscribe to custom events. Works client and server side. Weighs less than 1KB.
Demo and documentation can be found here
With mitty every extended object can publish and listen to custom events. Objects can be both publishers and subscribers simultaneously. Mitty provides a simple api for one object to listen to it's own events or subscribe to some other object events.
Supports all browsers that are ES5-compliant (IE8 and below are not supported).
Examples and api
on and trigger
Subscribe object to events with on(), publish events with trigger().
// start with simple objectvar musician = name: 'George'; // use "mitty" function to augment object with event api; // subscribe to play eventmusician; // trigger / publish "play" event with custom message as data// outputs 'George is currently playing. With style!'musician;
off
Remove events with off()
// Remove subscriptionmusician; // Trigger does nothing since we removed subscriptionmusician;
listenTo and stopListening
Use listenTo() when you want to subscribe to some other object events. Invoke stopListening() when you want to remove those subscriptions.
var instrument = ; instrument; // Outputs 'George is playing Guitar with grace!'musician; // Remove subscriptioninstrument; // Will not outputmusician;
once and listenToOnce
Use once() and listenToOnce() when for executing one time event listeners.
var musician = ; musician; musician; console // outputs 1
var musician = ;var instrument = ; instrument; musician; console // outputs 1
Augmenting objects
Types / prototype based constructor functions can also be augmented with events like so:
{ thisname = name;} ; var john = 'John'; john; john; // outputs 'John says hello'
Installation
Mitty types is packaged as UMD library so you can use it both on client and server (CommonJS and AMD environment) or with browser globals.
// install via npmnpm install mitty --save // if you use bundlervar mitty = ; // or use browser globalsvar mitty = windowmitty;