Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

happened

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

happened

Small and nice PubSub and event bus library with custom dispatcher support.

  • 0.9.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2.9K
decreased by-8.26%
Maintainers
1
Weekly downloads
 
Created
Source

happened

NPM version GitHub version Build Status Dependency Status

happened is a tiny PubSub library (~730 bytes minified and gzipped). It's designed to be an easy replacement for any other PubSub library (e.g. Backbone.Events), but also because of it's tiny size, it's a good choice for any other client-side that wants to provide events without external dependencies.

Examples

happened tries to cover all common use cases for PubSub:

Global Event Bus

Sometimes you just want a zero-hassle global event bus. happened provides pre-initialized global to support this use case:

var happened = require('happened');
happened.global.on('disco', function () {
    console.log('dance');
});
happened.global.trigger('disco'); // "dance"

Public Channels

happened supports public channel setup by calling happened.channel method:

var happened = require('happened');
var radioOne = happened.channel('radio1');
radio1.on('morning-broadcast', function () {
    console.log('wake up');
});

// in another place
happened.channel('radio1').trigger('morning-broadcast', 'impossible'); // "wake up"

Private Channels

Calling happened without any parameters will always construct a new instance, that can be used as an event

var happened = require('happened');
var topSecretMessages = happened.create();
topSecretMessages.on('mission', function () {
    console.log('completed');
});
topSecretMessages.trigger('mission', 'impossible'); // "completed"

Mixin for Objects

It's a very common need to have PubSub methods directly exposed on some object, or all objects of a given class. This is usually solved by providing a mixin (e.g. Backbone.Events), which has a downside of a need to define a property on an object, that can conflict with your own properties, or even cause compiler deoptimization if it's injected dynamically by on method.

All the methods on happened can be called in any context, so that means that they can be simply copied to a newly constructed instance in the constructor:

var happened = require('happened');

function Artist() {
    var events = happened.create();
    // you can choose which methods to copy from happened
    this.on = events.on;
    this.once = events.once;
    this.off = events.off;
    this.trigger = events.trigger;
    
    // additionally if you want to provide support to subscribe
    // to all events it's a good idea to copy corresponding constant
    this.ALL_EVENTS = events.ALL_EVENTS;
}

var superMetalBand = new Artist();
superMetalBand.on('concert', function () {
    console.log('scream');
});
superMetalBand.trigger('concert'); // "scream"

Since this is quite verbose happened provides a helper method for this common case:

function Artist() {
    happened.addTo(this);
}

NOTE: setScheduler method is not copied by addTo and in general is considered a bad practice.

More Good Stuff

  • Zero dependencies
  • Minimal interface (on, once, off, trigger), with utility methods exposed only on a global object.
  • UMD package
  • Support for custom schedulers.
  • Support for legacy browsers like IE6-8 and Android 2.3
  • Node.js support
  • all happened instances are frozen (immutable) if supported by environment

Requirements

happened by default uses asynchronous event dispatching. If you want events to be dispatched faster, you can use setScheduler to inject other schedulers, such as setImmediate for macro-task behavior or process.nextTick for micro-tasks.

Default async (setTimeout) mode is supported for all mainstream browsers and Node.js, but may not work in some esoteric environments, like Qt QML. In this it falls back to synchronous scheduler.

API

This section contains reference for all public methods and properties of happened, to see example usage please refer to examples section instead.

Type signatures for methods are presented using flow syntax.

Top-Level Library Methods and Properties

happened.global

This a preconstructed instance of happened that can be used as a global event bus.

happened.create()

Constructs a new instance of happened.

happened.create() => HappenedInstance
happened.channel()

Given the same name will always return the same singleton instance of happened, creating it if necessary. Allows for channel-style usage.

happened.channel(name : string) => HappenedInstance
happened.addTo()

This is convenience method to create a new instance of happened and copy it's methods on, once, off, trigger and a constant ALL_EVENTS to a given target:

happened.addTo(target : Object) => HappenedInstance
happened.setDefaultScheduler()

Changes current scheduler to a provided one. scheduler is simply a function that accepts a callback that is guaranteed to be executed at some point in the future, and also guarantees that callbacks will be executed in the same order as they were submitted to scheduler. setTimeout (used by default in happened) and process.nextTick are good examples of such a function.

happened.setDefaultScheduler(scheduler : (callback : void) => void) => void

If you want your events to be dispatched synchronously, you can add following statement before and usages of happened:

happened.setDefaultScheduler(happened.SYNC);

Instance Methods

on

This method is used to subscribe for a certain event:

happened.global.on(
    name     : string,
    callback : (...params) => void,
    thisArg  : Object?
) => void

The callback will receive all the parameters except for the name of the event from trigger as it's arguments. thisArg is optional context for callback.

Special case here is subscribing to all events, happening on the instance. To do this you need to provide ALL_EVENTS constant property available on all instances.

happened.global.on(
    happened.ALL_EVENTS,
    callback : (name : string, params : Array<any>) => void,
    thisArg  : Object?
) => void

NOTE: callback for all events has a different signature to a regular one, due to a need to pass event name.

once

Same as on, but causes the callback to only fire once before being offed.

happened.global.once(
    name     : string,
    callback : (...params) => void,
    thisArg  : Object?
) => void
off

Removes a specific callback for an event with a given name.

happened.global.off(
    name     : string?,
    callback : Function?
) => void

If called without callback, removes all callbacks for given name.

If called without any arguments, remove all callbacks for all events.

trigger

Triggers callbacks for the given event name, additional ...params to trigger will be passed along to the event callbacks.

happened.global.trigger(
    name      : string,
    ...params : any
) => void
setScheduler

Allows you to change scheduler for a particular instance:

happened.global.setScheduler(scheduler : (callback : void) => void) => void;

Contributing

Setting Up Development Environment

To start do a fork of this repo, clone it locally and type in your terminal:

npm install
gulp tdd

This will continuously run tests for nice dev experience. To run tests just once or in CI environment you can use:

gulp test

To build for production run:

gulp build

License

© 2015 Dmitriy Kubyshkin. Licensed under the MIT style license.

FAQs

Package last updated on 28 Apr 2015

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc