Skip to main content
Version: v0.x (deprecated)

PubSub & PubSubMixin

This version is deprecated

This documentation is for use-less-react v0.x, which has been deprecated.
See v1.0 documentation for the current API.

Lightweight reactive event emitter designed for fine-grained UI reactivity and class-based data models.


Overview

PubSub implements a minimal publish/subscribe mechanism that allows any class to notify observers when one or more of its properties change. It's the core of the reactivity model used in use-less-react v0.x.


PubSub

Define a class extending PubSub

import { PubSub } from '@dxbox/use-less-react/classes';

class Counter extends PubSub {
count = 0;

increment() {
this.count++;
this.notify('count');
}
}

Notify changes

counter.notify('count'); // notify single attribute
sprite.notify('x', 'y'); // notify multiple attributes

Subscribe to changes

sprite.subscribe((propNames) => {
if (propNames.includes('x')) {
const x = sprite.x; // retrieve value
}
});

Use onNotify

sprite.onNotify(['x'], ({ x }) => {
// do something with x
});

PubSubMixin

PubSubMixin provides the same functionality as PubSub but as a mixin, allowing you to add reactivity to existing classes without inheritance.

import { PubSubMixin } from '@dxbox/use-less-react/classes';

class Counter extends PubSubMixin() {
count = 0;
}

makeReactiveProperties

Use makeReactiveProperties to automatically define reactive setters that notify when properties change.

class MyStore extends PubSub {
counter: number = 0;
message: string = 'Hello';

constructor() {
super();
// Declares which properties should receive a reactive setter
this.makeReactiveProperties('counter', 'message');
}

incrementCounter() {
this.counter += 1; // this.notify("counter") is automatically called!
}
}

Important: It's intended to be used inside the constructor, as the last instruction.

It will throw if used on functions.


Notify derived values

You can notify a derived value calculated via a get method:

export class Sprite extends PubSub {
private x = 0;
private y = 0;

public get position() {
return { x: this.x, y: this.y };
}

@Notifies('position')
public setPosition(x: number, y: number) {
this.x = x;
this.y = y;
}
}

When setPosition notifies position, everything will work like with a standard class attribute.


Next: See Decorators for @Notifies and other decorators.

Migration: See v1.0 ReactiveObject for the modern equivalent.