项目作者: alexeyraspopov

项目描述 :
Observer done right
高级语言: JavaScript
项目地址: git://github.com/alexeyraspopov/newsletter.git
创建时间: 2014-06-21T08:58:21Z
项目社区:https://github.com/alexeyraspopov/newsletter

开源协议:MIT License

下载


newsletter

  1. npm install newsletter

Simple pub/sub implementation.

ESM Package

Starting from v4.0 this package fully moved to ES Modules and ES2015 code. This means no more
build step before publishing to NPM.

Ideally you shouldn’t spot any difference, but in case you face any issues, see
this useful article.

You can also downgrade to v3.x to use all the same functionality, precompiled to ES5.

API

To create publisher instance use Newsletter constructor (see Usage). Instance implements next
interface:

  • publish - invokes all listeners and pass some received data to them
  • subscribe - adds new listener (function) and returns subscription handling instance

Usage

  1. // get newsletter
  2. import { Newsletter } from "newsletter";
  3. // create instance
  4. var signal = new Newsletter();
  5. // subscribe notifications
  6. var subscription = signal.subscribe((data) => console.log(data));
  7. // publish some data to subscribers
  8. signal.publish(13);
  9. // remove listener
  10. subscription.dispose();

There is a way to subscribe to a single update

  1. var signal = new Newsletter();
  2. // subscribe to a single update
  3. var subscription = signal.subscribe((data) => {
  4. subscription.dispose();
  5. console.log(data);
  6. });
  7. // will call a listener and remove it
  8. signal.publish(13);
  9. // no listeners called
  10. signal.publish(14);

AbortSignal API can be used to
dispose a subscription:

  1. var pubsub = new Newsletter();
  2. var ctrl = new AbortController();
  3. // subscribe to a single update, pass AbortSignal as second param
  4. pubsub.subscribe((data) => {
  5. console.log(data);
  6. }, ctrl.signal);
  7. // will call a listener, as expected
  8. pubsub.publish(13);
  9. // abort controller can be aborted at any occasion
  10. ctrl.abort();
  11. // no listeners called
  12. pubsub.publish(14);

The project is licensed under the MIT license.