Skip to content

Actions and Stores for FLUX

Fred Chien edited this page Oct 31, 2015 · 2 revisions

FLUX Pattern FLUX pattern is the fundamental architecture Lantern used, which includes Actions, Stores and Views, the data flow in only one direction on. With Fluky, everything is asynchronous event. Actions and stores are easily created with event listening mechanism.

Implementation

Fluky Lantern used is an event-based FLUX framework that implemented Actions and Stores with general event mechanism. All of actions and stores are processed by passing event dispatcher.

Actions

Step 1: Create a Action File

Create a new JavaScript file in the ./src/js/actions, and write a generator function in it like below:

Example foo.js:

export default function *() {

};

Step 2: Listen to Action Event

export default function *() {
    this.on('action.Foo.doSomething', function *() {
        // do something...
    });
};

Step 3: Forward Event to Store if Necessary

export default function *() {
    this.on('action.Foo.doSomething', function *() {
        this.dispatch('store.Foo.doSomething');
    });
};

Note that Fluky will forward events with a new event name store.* to Stores automatically if no action event listener.

Step 4: Add to Actions List

Write the file name above to ./src/actions/index.js.

export default {
    Foo: require('./foo.js')
};

Stores

Step 1: Create a Store File

Create a new JavaScript file in the ./src/js/stores, and write a generator function in it like below:

Example foo.js:

export default function *() {

};

Step 2: Listen to Store Event

export default function *() {
    this.on('store.Foo.doSomething', function *() {
        // do something...
    });
};

Step 3: Create a State to Store Data with initial values

export default function *() {
    var store = this.getState('Foo', {
        key1: 100,
        key2: 'Hello'
    });

    this.on('store.Foo.doSomething', function *() {
        // do something...
    });
};

Step 4: Getting and Updating State

export default function *() {
    var store = this.getState('Foo', {
        key1: 100,
        key2: 'Hello'
    });

    this.on('store.Foo.doSomething', function *() {
        var state = this.getState('Foo');

        // Updating state
        state.key1++;

        // Fire event to tell all of listeners that `state.Foo` was changed
        this.dispatch('state.Foo');
    });
};

Step 5: Add to Stores List

Write the file name above to ./src/stores/index.js.

export default {
    Foo: require('./foo.js')
};