Coder Social home page Coder Social logo

material-flux's Introduction

material-flux Build Status

No magic flux implementation library.

  • Less trick
    • No method swizzle, No overwrite function
    • IDE Readable API(Machine Readable API)
  • Debuggable
  • ECMAScript6 compatible
  • Class syntax

Installation

npm install material-flux

Usage

material-flux is consist of Action, Store and Context.

Flux Architecture

User action -> Action -> Context dispatch -> Store received dispatch -> Store dispatch "change" event -> View received the "change". -> update view.

flow image

  • Context provide dispatch function to Actions.
  • Context register store for dispatched event.
  • Action dispatch event.
  • Store received dispatched event with data.
  • Store dispatch "change" event when update state in the store.

Action

import {Action} from "material-flux"
// it's a like constants
export const keys = {
    // "any key" : "any value"
    "doSomething": "unique value"
};
export default class UserAction extends Action {
    doSomething(data) {
        // pass the `data` to Store's `onHandler`
        // call `onHandler(data);`
        this.dispatch(keys.doSomething, data);
    }
}

When you call action, dispatch store's handler.

Store

import {keys} from "./UserAction.js"
import {Store} from "material-flux"
export default class UserStore extends Store {
   constructor(...args) {
       super(...args);
       this.state = {
           userData: null
       };
       this.register(keys.doSomething, this.onHandler);
   }

   // data is come from Action
   onHandler(data) {
       this.setState({
           userData: data
       });
   }

   // just getter method
   getUserData() {
       return this.state.userData;
   }
}

Store#onChange(listener)

Adds a listener to the end of the listeners array for the "change" event.

  • listener is a function.

Store#removeChangeListener(listener)

Removes a "change" listener.

  • listener is a function.

Store#removeAllChangeListeners()

Removes all "change" listeners.

Store#getState()

Return state object that shallowly clone store's state.

Store#setState(object)

Update this.state and emit "change" event.

  • object is any object.

Context

How to connect Action and Store? => Create connection object. it is called Context in this context.

import UserAction from "./UserAction.js"
import UserStore from "./UserStore.js"
import {Context} from 'material-flux';
export default class UserContext extends Context {
    constructor() {
        super();
        this.userAction = new UserAction(this);
        this.userStore = new UserStore(this);
    }
}

View(Component)

How to connect to View like React? => Pass an instance of Context to React's Component.

import React from 'react';
import UserContext from './UserContext.js';
import App from './AppComponent.jsx';
var context = new UserContext();
React.render(
    React.createElement(App, { context }),
    document.getElementById('main')
);

AppComponent:

import React from 'react';
export default class AppComponent extends React.Component {
    constructor(...args) {
        super(...args);
        this.userStore = this.props.context.userStore;
        this.state = {
            userData: this.userStore.getUserData()
        };
    }

    _onChange() {
        this.setState({
            userData: this.userStore.getUserData()
        });
    }

    componentDidMount() {
        this.userStore.onChange(this._onChange.bind(this));
    }

    componentWillUnmount() {
        this.userStore.removeAllChangeListeners();
    }

    onClick(event) {
        var { context } = this.props;
        context.userAction.doSomething("clicked");
    }

    render() {
        return (
            <div onClick={this.onClick.bind(this)}>
                userData: {this.state.userData}
            </div>
        );
    }
}

Container

If you want to Container Component, use https://github.com/azu/material-flux-container

Examples

more examples.

Tests

npm test
# it run mocha & npm run test:typing.

Contributing

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

License

MIT

Inspiration and thanks

material-flux's People

Contributors

azu avatar ykhs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

kiikurage ykhs

material-flux's Issues

Provide d.ts

Create TypeScript type definitions for material-flux

assert to pass wrong arguments

var action = new Action({ "wrong" : "arguments" });

should be thrown.
Parent class constructor need to assert( args is valid ).

dispatch(key, payload) : key should not object

dispatch(eventKey, ...args) {
this.dispatcher.dispatch({
eventKey,
args
});
this.emit('dispatch', {eventKey, args});
}

    dispatch(eventKey, ...args) {
        this.dispatcher.dispatch({
            eventKey,
            args
        });
        this.emit('dispatch', {eventKey, args});
    }

eventKey should be string | Symbol like object's key.
if eventKey is typeof object, assert this as error.

dispatch({
    type : "HANDLE_SOME",
    data : "data"
});
// throw error

It aim to prevent confusion of usage with other flux library like Redux, Facebook's flux etc...

I'v met similar issue on fluxible's Action.

feature: Add StoreGroup

StoreGroup is collection of stores are instance of MaterialStore.
All Store are dispatched then call callback function.

var context = new Context();
var stores = [new UserStore(context), new UserStore(context), new UserStore(context)];
var group = new StoreGroup(stores, function allDispatched() {
    var dataList = stores.map(store => {
        return store.getUserData();
    }).filter(data => data != null);
    assert.equal(dataList.length, stores.length);
    done();
});
var data = {"key": "value"};
context.dispatch(eventKey, data);

// release group

group.release();

feature: Add Container

Container of flux-utils is very useful.
We want to add Container to material-flux.

import { Container } from "material-flux"
Container.crate(AppComponent);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.