Skip to content
Christian Alfoni edited this page Mar 5, 2015 · 11 revisions

In addition to the three basic concepts, Tree, Event hub and Components, you will need business logic. This is the part that controls the state of your application. The business logic can listen to events triggered by components and it can reach into the tree to change the state.

Let us imagine we want to add new todos. When doing so we want to post them to the server and control the, pending, success and error of that operation.

addTodo.js

var tree = require('./tree.js');
var ajax = require('ajax'); // Some promise based ajax lib
var utils = require('./utils.js');

// Lets look at the tree
tree.get(); // { todos: [] }

var addTodo = function (title) {

  // Create the client version of the object with
  // a temporary ID for reference
  var todo = {
    id: utils.createId(),
    title: title,
    completed: false,
    isPending: true,
    error: null
  };
  
  // Optimistic update
  tree.select('todos').unshift(todo);

  // Create a cursor for later update
  var todoCursor = tree.select('todos', {id: todo.id});

  // Post the server side version of the object and
  // return a promise
  return ajax.post('/todos', {
    title: todo.title,
    completed: todo.completed
  })
  .success(function (todoId) {
    todoCursor.merge({
      isPending: false,
      id: todoId
    });
  })
  .error(function (error) {
    todoCursor.merge({
      isPending: false,
      error: error
    });
  });
};

module.exports = addTodo;

We create a controller that binds the events to the actions. This gives you a list of how events triggered from components, or other parts of your business logic, will run.

main.js

var React = require('react');
var events = require('./events.js');
var App = require('./App.jsx');
var addTodo = require('./addTodo.js');

events.on('addTodo', addTodo);

React.render(<App/>, document.body);