2.0.5 • Published 8 years ago

hookies v2.0.5

Weekly downloads
2
License
MIT
Repository
github
Last release
8 years ago

Build Status Code Climate Test Coverage Dependency Status

hookies

Hookies is a very simple object specific publish/subscribe library. Hookies allows you to create "as many as you need" independent objects that will enjoy it's own on|off and trigger methods. Let me give you an example:

import { Hooks } from 'hookies';

class Cat extends Hooks {
  constructor(name) {
    super();
    this.name = name;
  }
}

class Mouse extends Hooks {
  constructor(name) {
    super();
    this.name = name;
  }
}

const tom = new Cat('Tom');
const jerry = new Mouse('Jerry');

// tom subscribes to `detect-mouse` event.
tom.on('detect-mouse', function (mouse) {
  console.log(this.name + ' has detected ' + mouse.name);

  mouse.hookies.trigger('detected-by-cat', this);
});

jerry.on('detected-by-cat', function (cat) {
  console.log(this.name + ' runs away, because ' + cat.name + ' is chasing him.');
});

tom.trigger('detect-mouse', jerry);

// This will produce following output:
//
// Tom has detected Jerry
// Jerry runs away, because Tom is chasing him.

Installation

As simple as:

npm install hookies

Usage

import { Hooks } from 'hookies';

const myHookie = new Hooks();

// Second argument can be optionally and object which will represent `this`
// inside a callback
myHookie.on('foo', { name: 'John' }, function () {
    console.log(this.name, arguments);
});

myHookie.trigger('foo', 1, 2, 3);
// John [1, 2, 3]

Callback functions are executed asynchronously by default, but you can force them to run synchronously too:

import { Hooks } from 'hookies';

const myHookie = new Hookies.Hooks();

myHookie.on('foo', { name: 'John' }, function () {
  console.log(this.name, arguments);
});

myHookie.trigger({
  name: 'foo',
  sync: true, // run synchronously
  // you can overwrite `this` inside callback function whenever you need to
  context: { name: 'Bob' }
}, 1, 2, 3);

console.log('I am sync');

myHookie.trigger('foo', 1, 2, 3);

console.log('I am async');

// Bob [1, 2, 3]
// I am sync
// I am async
// John [1, 2, 3]

License

The MIT License (MIT) - See file 'LICENSE' in this project

Copyright

Copyright © 2016 Jiri Chara. All Rights Reserved.

2.0.5

8 years ago

2.0.4

8 years ago

2.0.3

8 years ago

2.0.2

8 years ago

2.0.1

8 years ago

2.0.0

8 years ago

1.0.7

9 years ago

1.0.6

9 years ago

1.0.5

9 years ago

1.0.4

9 years ago

1.0.3

10 years ago

1.0.2

10 years ago

1.0.1

10 years ago

1.0.0

10 years ago