Skip to content
Dimitar Marinov edited this page Nov 10, 2022 · 4 revisions

Counter example

Step 1: Create db and register update handlers

const db = {
    count: 0
};

xf.create(db);	

xf.reg('count-set', (value, db) => {
    db.count = value;
});

xf.reg('count-inc', (_, db) => {
    db.count += 1;
});

xf.reg('count-dec', (_, db) => {
    db.count -= 1;
});

Step 2: Subscribe for state changes

const abortController = new AbortController();
const options = { signal: abortController.signal };

let count = 0;

xf.sub('db:count', function(value) => {
    count = value;
    console.log(count);
}, options);

Step 3: Dispatch updates

xf.dispatch('count-inc')     // db.count =  1, console.log:  1
xf.dispatch('count-dec')     // db.count =  0, console.log:  0
xf.dispatch('count-set', 10) // db.count = 10, console.log: 10

Step 4: Remove no longer needed event handlers:

abortController.abort();
xf.dispatch('count-set', 8)  // db.count = 8, console.log will not execute

xf.create

xf.create({property-name: Any,})

uses a simple proxy object with a set trap to intercept object property value changes. Every time the value at db.count is changed it will dispatch a custom event 'db:count' with the new value.

xf.reg

xf.reg(event-name: String, handler: Function(global-state: {}, new-value: Any))

is used to register update handler for a particular property on the db object. It has access to the whole global state object. It's the proper place to make changes to state. Here you change db.count from one value to the next.

xf.sub

xf.sub(event-name: String, handler: Function(updated-value: Any))

is used to subscribe for state changes. It has access only to the new value. Use this in places like the Views. Subscribing to 'db:count' will notify you for changes to db.count

xf.dispatch

xf.dispatch(event-name: String, optional-new-value: Any)

is used to send new values to db.

Clone this wiki locally