Giter Club home page Giter Club logo

biff's Introduction

#Biff Flux Architecture Made Easy

What is Biff?

When writing ReactJS apps, it is enormously helpful to use Facebook's Flux architecture. It truly complements ReactJS' unidirectional data flow model. Facebook's Flux library provides a Dispatcher, and some examples of how to write Actions and Stores. However, there are no helpers for Action & Store creation, and Stores require 3rd part eventing.

Biff is a library that provides all 3 components of Flux architecture, using Facebook's Dispatcher, and providing factories for Actions & Stores.

###Demo

Check out this JSFiddle Demo to see how Biff can work for you:

http://jsfiddle.net/2xtqx3u3/

###Getting Started

The first step to using Biff is to create a new instance of Biff.

####Standalone

var biff = new Biff();

####Modular

var Biff = require('biff');
module.exports = new Biff();

Each instance of Biff has its own Dispatcher instance created and attached.

In fact, all created Actions & Stores are also stored on the Biff object as actions and stores respectively.

biff.dispatcher // Dispatcher instance
biff.actions // Array of actions
biff.stores // Array of stores

###Stores

Biff has a createStore helper method that creates an instance of a Store. Store instances have been merged with EventEmitter and come with emitChange, addChangeListener and removeChangeListener methods built in.

When a store is created, its methods parameter specified what public methods should be added to the Store object. Every store is automatically registered with the Dispatcher and the dispatcherID is stored on the Store object itself, for use in waitFor methods.

Creating a store with Biff looks like this:

// Require the Biff instance you created
var biff = require('./biff');

// Internal data object
var _todos = [];

function addTodo(text) {
  _todos.push(text);
}

var TodoStore = biff.createStore({

getTodos: function() {
  return _todos;
}

}, function(payload){

  switch(payload.actionType) {
  case 'ADD_TODO':
    addTodo(payload.text);
    this.emitChange();
  break;
  default:
    return true;
  }

  return true;

});

Use Dispatcher.waitFor if you need to ensure handlers from other stores run first.

var biff = require('./biff');
var Dispatcher = Biff.dispatcher;
var OtherStore = require('../stores/OtherStore');

var _todos = [];

function addTodo(text, someValue) {
  _todos.push({ text: text, someValue: someValue });
}

 ...

    case 'ADD_TODO':
      Dispatcher.waitFor([OtherStore.dispatcherID]);
      var someValue = OtherStore.getSomeValue();
      addTodo(payload.text, someValue);
      break;

 ...

Stores are also created a with a ReactJS component mixin that adds and removes store listeners that call an storeDidChange component method.

Adding Store eventing to your component is as easy as:

var TodoStore = require('../stores/TodoStore');

var TodoApp = React.createClass({

  mixins: [TodoStore.mixin],
  storeDidChange: function () {
    // Handle store change here
  }

  ...

This mixin also adds listeners that call a storeError component method, so that if you call this.emitError('Error Messaging') in your store, you can respond and handle this in your components:

var TodoStore = require('../stores/TodoStore');

var TodoApp = React.createClass({

  mixins: [TodoStore.mixin],
  storeError: function (error) {
    console.log(error);
  }

  ...

A simple example of how this works can be seen here:

http://jsfiddle.net/p6q8ghpc/

Stores in Biff also have helpers for managing the state of the store's data. Each Biff instance has _pending and _errors properties. These are exposed via getters and setters. These methods are:

  • getPending() - Returns store pending state
  • getErrors() - Returns store errors array
  • _setPending(arg) - Sets store pending state
  • _setError(arg) - Adds an error to the store errors array
  • _clearErrors() - Clears store errors array

Below, see an example of how they can be used:

// In Your Store

var TodoStore = biff.createStore({
    getTodos: function() {
      return _todos;
    }

}, function(payload){

  switch(payload.actionType) {
    case 'ADD_START':
      this._setPending(true);
    break;

    case 'ADD_SUCCESS':
       this._setPending(false);
      addTodo(payload.text);
      this._clearErrors();
      this.emitChange();
    break;

    case 'ADD_ERROR':
      this._setPending(false);
      this._setError(payload.error);
      this.emitChange();
    break;

    default:
      return true;
  }

  return true;

});

// In your component

function getState(){
  return {
    errors: TodoStore.getErrors()
    pending: TodoStore.getPending()
    todos: TodoStore.getTodos()
  }
}

var TodoApp = React.createClass({
  mixins: [TodoStore.mixin],
  getInitialState: function () {
    return getState();
  },
  storeDidChange: function () {
    this.setState(getState());
  }
  ...

###Actions

Biff's createActions method creates an Action Creator object with the supplied singleton object. The methods of the supplied object are given an instance of the Biff instance's dispatcher object so that you can make dispatch calls from them. It is available via this.dispatch in the interior of your methods.

Adding actions to your app looks like this:

var biff = require('../biff');

var TodoActions = biff.createActions({
  addTodo: function(text) {
    this.dispatch({
      actionType: 'ADD_TODO',
      text: text
    });
  }
});

Async In Biff

Check out the example below to show you can handle async in Biff:

http://jsfiddle.net/29L0anf1/

API

###Biff

var Biff = require('biff');

module.exports = new Biff();

createStore

/*
 * @param {object} methods - Public methods for Store instance
 * @param {function} callback - Callback method for Dispatcher dispatches
 * @return {object} - Returns instance of Store
 */

createActions

/**
 * @param {object} actions - Object with methods to create actions with
 * @constructor
 */

biff's People

Contributors

balanceiskey avatar bigblind avatar dbellizzi avatar eastridge avatar kenwheeler avatar mbjorkegren avatar ncherro avatar tomatau avatar tracker1 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

Watchers

 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

biff's Issues

Add server rendering helpers

It would be nice to have the ability to snapshot the entire Flux setup on the server and then boot from the snapshot once the client loads up.

Refactor Testing

Switch from Jest to a Mocha/Sinon/Karma/Instanbul test setup.

Biff and ES6

admittedly, I'm newer to the syntax of ES6 and ESNext but I am curious as to what Biff's syntax would be for creating stores?

export class SomeStore extends Biff.createStore{
  _store = [];
  addStoreItem(item){
    this._store.push(item);
  }
  //etc...
}

That is the equivalent of what I have so far, but I can't seem to figure out how to add the dispatcher handler function to the class. Am I way off base and using class incorrectly, or does Biff not have support for ES6?

Biff vs McFly

So what's the difference between the two? Was Biff created simply so it can live under FormidableLabs? Will McFly continue to be maintained or is Biff now preferable?

Component listening to multiple stores with ES6 syntax

How do I add multiple stores to a React component using ES6 syntax?

Building an application where there is a loader component which is shown until multiple stores have loaded. On each store update the component would look up if the store is ready by calling a store method. Could it be a bad practise to do so? Alternatives?

EDIT
For now just opted to add events manually by using MyStore.addChangeListener in the MyComponent.componentDidMount method, the same as the store mixing would do automatically.

May close this "issue"!

Simple Console error when rendering to String

Getting error when doing a React.renderToString.
biff/node_modules/simple-console/simple-console.js: line 104.
Might need to change
_console = window.console || null;
to
_console = ( window && window.console ) ? window.console : null;

_this.storeDidChange is not a function

I've created a Store called RegistrationStore and added this to react component

RegistrationStore.mixin

The first time storeDidChange is called everything works as expected. I have a child component that calls the parent component when a button is clicked and I ran into this problem.

TypeError: _this.storeDidChange is not a function
    at Store.mixin.componentDidMount.listener (Store.js:59)
    at Store.EventEmitter.emit (events.js:99)
    at Store.emitChange (Store.js:154)
    at Store.<anonymous> (RegistrationStore.js:46)
    at Store.<anonymous> (Store.js:14)
    at Dispatcher.$Dispatcher_invokeCallback (Dispatcher.js:220)
    at Dispatcher.dispatch (Dispatcher.js:195)
    at Action.Biff.createActions.storeSectionFields [as callback] (RegistrationAction.js:41)
    at React.createClass.onSectionSubmit (ModuleRegistrationComponent.jsx:88)
    at React.createClass.submit (SectionComponent.jsx:56)

here is my onSectionSubmit

onSectionSubmit: function(model,transition){
        var data = [];
        this.state.fields.map(function(field){
           if( model[ field._id ] ){
               if( field.type === 'dropdown' ){
                    data.push( {_id : field._id, value : model[field._id].split(',') } );  
               }else{
                    data.push( { _id : field._id, value : model[field._id] });   
               }

           }
        });

       // Here is where the error happens.
        RegistrationAction.storeSectionFields(  data );  
    },

This is my store and my action

var Biff = require("../biff");
var request = require("superagent");



var RegistrationAction = Biff.createActions({

    checkEmail: function(data) {
        var self = this;
        request
            .post("/users/create")
            .send({ user : data})
            .set("Accept", "application/json")
            .set('Content-Type', 'application/json')
            .end(function (error,res) {
                console.log( res.text );
                self.dispatch({
                    actionType: "REGISTRATION_CHECK_EMAIL",
                    data: JSON.parse(res.text)
                });
            });

    },
    getSectionFields : function( data ){
        var self = this;
        request
            .post("/fields/get")
            .send({ sectionId : data})
            .set("Accept", "application/json")
            .set('Content-Type', 'application/json')
            .end(function (error,res) {
                self.dispatch({
                    actionType: "REGISTRATION_FIELDS_GET",
                    data: JSON.parse(res.text)
                });
            });
    },
     storeSectionFields : function( data ){
         console.log( "StoreSection" );
         console.log( data );
        this.dispatch({
            actionType: "REGISTRATION_FIELDS_STORE",
            data: data
        });

    },
    setCurrentSection : function( module ){
        this.dispatch({
            actionType: "REGISTRATION_SET_SECTION",
            data: module
        });
    }
});

module.exports = RegistrationAction;
var Biff = require("../biff");

var RegistrationStore = Biff.createStore({

    _user: {},
    _module: {},
    _fields:{},
    _enteredFields:[],

    checkEmail: function (data) {
        this._user = data;
    },
    getUser : function(){
      return this._user;
    },
    setCurrentSection :function(data){
        this._module = data;
    },
     setCurrentSectionFields :function(data){
        this._module = data;
    },
    getCurrentSection: function(){
        return this._module;
    },
    setSectionFields: function(data){
       this._fields = data;
    },
    getSectionFields: function(){
        console.log( "Getting section" );
        console.log( this._fields );
        return this._fields;
    },
    storeSectionFields: function(fields){
        this._enteredFields.push( fields );
    }

}, function (payload) {

    switch( payload.actionType ){
        case 'REGISTRATION_FIELDS_GET':
            this.setSectionFields(payload.data);
            this.emitChange();
            break;
        case 'REGISTRATION_FIELDS_STORE':
            this.storeSectionFields(payload.data);
            this.emitChange();
            break;
        case 'REGISTRATION_CHECK_EMAIL':
            if( payload.data.error){
                this.emitError( payload.data.error );
            }else {
                this.checkEmail(payload.data);
                this.emitChange();
            }
            break;
        case 'REGISTRATION_SET_SECTION' :
            this.setCurrentSection(payload.data);
            this.emitChange();
            break;
    }



});

module.exports = RegistrationStore;

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.