Flux intro

This presentation available at slonoed.net/flux-intro

by Dmitry Manannikov / @slonoed

What is ReactJS?

React is view part

And only view part of application

React components

  • Small
  • Easy to test
  • Loose coupled

Simple react component

Render process

React can:

  • Render in efficient way
  • Handle user events
  • Render on server


React can't:

  • Make AJAX calls
  • Deal with data
  • App structure
  • etc...

What is Flux?

Flux is an idea

about how to manage dataflow in complex applications

Flux is not

  • Framework
  • Library
  • MVC

Dispatcher is event system

Dispatcher is global object


var MyDispatcher = new Dispatcher();                          
                    

createNewItem: function() {
    MyDispatcher.dispatch({
        type: 'newMessage',
        message: { text: 'New message', id: Math.random() }
    });
} 
                

var MessageStore = {
    messages: [], // this is data model

    getMessages: function() {
        return this.messages;
    }
 };

 MyDispatcher.register(function (payload) {
    switch(payload.type) { // not a beauty way...
        case: 'newMessage': 
            MessageStore.messages.push(payload.message);
            break;
    }
 });
                

Store is not a model!

Store contains models

Store contain application state

Only stores can register dispatcher callbacks

Store is dingle "domain"


MicroEvent.mixin(MessageStore);  
                

                    
case: 'newMessage': 
    MessageStore.messages.push(payload.message);

    MessageStore.emit('change');

    break;                        
                

componentDidMount: function() {  
    MessageStore.bind('change', this.onStoreChanged);
},

onStoreChanged: function() {  
    this.setState({
        messages: MessageStore.getMessages()
    });
},

componentWillUnmount: function() {  
    // important to unbind handler when component unmount
    MessageStore.unbind('change', this.onStoreChanged);
}
                

render()

Is this a good way to re-render entire component every time the store updated?

Yes. Because in reality javascript is fast. DOM is slow.

Why it’s so cool?

AJAX and Action Creators


var Api = require('./api');

var messageActions = {
    
    add: function(text) {

        Api.createMessage(text).then(function(message) {

            MyDispatcher.dispatch({
                type: 'newMessage',
                message: message
            });

        });
    }
};                        
                    

General questions

  • How to communicate between components?
  • How to fetch server data?
  • Should I use model library?
  • Which Flux framework is the best?
  • Can I use Flux on server?

Thank you! Questions?


This presentation available at slonoed.net/flux-intro

Follow me at twitter @slonoed