flux-common-store

1.2.0 • Public • Published

flux-common-store

Dependency Status devDependency Status

Flux Common Store

Installation

npm install --save-dev flux-common-store

API

CHANGE_EVENT (change)

Constant event name, equals change

emitChange()

Emits CHANGE_EVENT

addChangeListener(callback): unsubscribeFunction

Adds callback listener for CHANGE_EVENT and returns unsubscribe function

removeChangeListener(callback)

Alternative way to unsubscribe from CHANGE_EVENT.

WARN For safety reasons, use unsubscribe function returned by addChangeListener instead

Usage

./stores/TodoStore.js

import FluxCommonStore from 'flux-common-store';
import Dispatcher from '../Dispatcher';
import Constants from '../Constants';
 
let todos = {};
 
const create = text => {
  const id = Date.now();
  todos[id] = {id: id, complete: false, text: text};
};
 
const destroy = id => delete todos[id];
 
const TodoStore = {
  ...FluxCommonStore,
 
  getAll() {
    return todos;
  }
};
 
TodoStore.dispatcherIndex = Dispatcher.register(({actionType, payload}) => {
  switch (actionType) {
    case Constants.TODO_CREATE:
      const text = payload.text.trim();
      if (text !== '') {
        create(text);
        TodoStore.emitChange();
      }
      break;
 
    case Constants.TODO_DESTROY:
      destroy(payload.id);
      TodoStore.emitChange();
      break;
 
    default:
    // Empty
  }
 
  return true;
});
 
export default TodoStore;

./components/TodoApp.js

import TodoStore from '../stores/TodoStore';
 
const TodoApp = React.createClass({
  getInitialState() {
    return {todos: TodoStore.getAll()};
  },
 
  componentDidMount() {
    // Subscribe to TodoStore changes which returns `unsubscribe` function
    this.unsubscribe = TodoStore.addChangeListener(this.onChange);
  },
 
  componentWillUnmount() {
    this.unsubscribe();
  },
 
  onChange() {
    this.setState({todos: TodoStore.getAll()});
  },
 
  render() {
    return (
      <ul>
        {this.state.todos.map(todo => <li key={todo.id}>{todo.text}</li>)}
      </ul>
    );
  }
});
 
export default TodoApp;

License

MIT

Package Sidebar

Install

npm i flux-common-store

Weekly Downloads

3

Version

1.2.0

License

MIT

Last publish

Collaborators

  • nkbt