Redux from scratch

In my post earlier today, I posted resources regarding this new flux-inspired library called Redux. After playing around with their two examples, I think I have a good idea of how it works now and I'd like to basically re-explain the library in my own words for two reasons: 1) it will help me solidify my understanding and 2) the docs for Redux is pretty good but is still a work-in-progress.

Redux essentially gently nudges you to a more a functional way of doing Flux-esque architecture which enables neat developer tools like their hot-loading / time machine as discussed in the video. Many more benefits are outlined by the author here.

State is in Dispatchers, Not Stores

The first place to start is to understand that all the state is now managed by the dispatcher and not the individual stores. The stores instead become essentially a collection of functions to update the state.

The app bootstraps from this:

Top-level Components get State from the Store

https://github.com/gaearon/redux#smart-components

I'm calling it top-level components to be more descriptive but technically it doesn't have to be top-level. You can also just think of these as the "stateful components".

So what's happening here is that the Connector is a parent component that's basically picking which state to get. Then, in the renderChild, the first parameter is the state that you have selected, and the second is a callback function for the dispatcher. You then do bindActionCreators, which binds the action creators to the dispatcher. You can see how it's implemented in the bindActionCreators.js file which is only 7 lines.

export default class TodoApp {
  render() {
return (
<Connector select={state => ({ todos: state.todos })}>
{this.renderChild}
</Connector>
);
}

renderChild({ todos, dispatch }) {
const actions = bindActionCreators(TodoActions, dispatch);
return (
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
);
}
}
So where does this state.todos get defined? It's in the stores!

Stores set initial state and then take in state from then on

Below is a store from the counter example in the repo. Here you are changing the state. This is where you can use immutable.js so you are not mutating the current state object.

import { INCREMENT_COUNTER, DECREMENT_COUNTER, INCREMENT_COUNTER_BY_THREE } from '../constants/ActionTypes';

export default function counter(state = 0, action) {
switch (action.type) {
case INCREMENT_COUNTER:
return state + 1;
case INCREMENT_COUNTER_BY_THREE:
return state + 3;
case DECREMENT_COUNTER:
return state - 1;
default:
return state;
}
}

Child (state-less) components hook to actions

I've pasted below a simplified version of the TodoItem from the TodoMVC example. Here, I've created an action to move a to do item to the top of the list, if you click on the "Move Up" link. The link triggers the moveTodoUp action which is passed into it from its parent component (and originates from the Top-level component where we did the bindActionCreators.

export default class TodoItem extends Component {
  static propTypes = {
moveTodoUp: PropTypes.func.isRequired
};

render() {
const {todo, markTodo, deleteTodo, editTodo, moveTodoUp} = this.props;
}

return (
{element} <a style={willStyles} onClick={()=>moveTodoUp(todo.id)}>Move up</a>
);
}
}

A simple action

The moveTodoUp action that you saw earlier is defined here in the ActionCreators file. It's pretty simple, all it does is return a type and what it was passed in.

export function moveTodoUp(id) {
  console.log("moveTodoUpId", id)
return {
type: types.MOVE_TODO_UP,
id
};
}

Conclusion

Overall, it was fun learning this library. I think it has some interesting concepts and the learning curve wasn't too bad. I think the docs can be organized a little better and have a few more examples (the TodoMVC and counter examples were great, so maybe including snippets from those in the docs itself). The one suggestion I would have is to see whether you can use the ES6 global symbol registry instead of having a separate file to write down constants for action strings.

Design Patterns

Summary of Design Patterns

http://addyosmani.com/resources/essentialjsdesignpatterns/book/#summarytabledesignpatterns

Below, I've copied his table and added my notes to help me remember each of the design 


Creational   Based on the concept of creating an object.
    
Class
Factory Method This creates an instance. In some cases, in can provide an instance of one of several related classes. In angular, the factory gives you back an instance (the author of the factory method should instantiate it for you) whereas a service returns the class and you must instantiate it yourself. (Factory, vs. Factory Method, vs. Abstract Factory: Stackoverflow - http://stackoverflow.com/a/13030163/4530617). Factory method is where you're overriding the method using a subclass.

Object
Abstract Factory Creates an instance of several families of classes without detailing concrete classes. Create a whole family of objects that are related. Abstract Factory allows you to instantiate a set (a family of classes)
Builder Use instead of factory when there's many parameters. You now only pass in the required members to the constructors and then invoke the rest through chained methods that return this (http://stackoverflow.com/a/1953567/4530617).mORIGINAL: Separates object construction from its representation, always creates the same type of object.
Prototype A fully initialized instance used for copying or cloning. https://carldanley.com/js-prototype-pattern/ Giving properties through prototypal inheritance
Singleton A class with only a single instance with global access points.




 Structural   Based on the idea of building blocks of objects.

    Object
      Adapter Match interfaces of different classes therefore classes can work together despite incompatible interfaces. create universal interface http://stackoverflow.com/a/3480547/4530617
      Bridge Separates an object's interface from its implementation so the two can vary independently. http://jsfiddle.net/juanmendez/g34F7/
      Composite The Composite Pattern describes a group of objects that can be treated in the same way a single instance of an object may be.
A structure of simple and composite objects which makes the total object more than just the sum of its parts. http://www.joezimjs.com/javascript/javascript-design-patterns-composite/
      Decorator Dynamically add alternate processing to objects.
      Facade A single class that hides the complexity of an entire subsystem.
      Flyweight A fine-grained instance used for efficient sharing of information that is contained elsewhere.
      Proxy A place holder object representing the true object.



Behavioral   Based on the way objects play and work together.
    Class
      Interpreter A way to include language elements in an application to match the grammar of the intended language.
      Template 
       Method
Creates the shell of an algorithm in a method, then defer the exact steps to a subclass.
    Object
      Chain of 
      Responsibility
A way of passing a request between a chain of objects to find the object that can handle the request.
      Command Encapsulate a command request as an object to enable, logging and/or queuing of requests, and provides error-handling for unhandled requests.
      Iterator Sequentially access the elements of a collection without knowing the inner workings of the collection.
      Mediator Defines simplified communication between classes to prevent a group of classes from referring explicitly to each other.
      Memento Capture an object's internal state to be able to restore it later.
      Observer A way of notifying change to a number of classes to ensure consistency between the classes.
      State Alter an object's behavior when its state changes.
      Strategy Encapsulates an algorithm inside a class separating the selection from the implementation.
      Visitor Adds a new operation to a class without changing the class.

Creational Design Patterns (creating objects)

Creational design patterns focus on handling object creation mechanisms where objects are created in a manner suitable for the situation we're working in. The basic approach to object creation might otherwise lead to added complexity in a project whilst these patterns aim to solve this problem by controlling the creation process.

Some of the patterns that fall under this category are: Constructor, Factory, Abstract, Prototype, Singleton and Builder.

Structural Design Patterns (composing objects together)

Structural patterns are concerned with object composition and typically identify simple ways to realize relationships between different objects. They help ensure that when one part of a system changes, the entire structure of the system doesn't need to do the same. They also assist in recasting parts of the system which don't fit a particular purpose into those that do.

Patterns that fall under this category include: Decorator, Facade, Flyweight, Adapter and Proxy.

Behavioral Design Patterns (communicating between objects)

Behavioral patterns focus on improving or streamlining the communication between disparate objects in a system.

Some behavioral patterns include: Iterator, Mediator, Observer and Visitor.



  1. Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used. The opposite of lazy loading is eagerloading.

Make for Javascript?

Few interesting articles on people using Make / makefile for javascript:

https://blog.jcoglan.com/2014/02/05/building-javascript-projects-with-make/

https://algorithms.rdio.com/post/make/

http://www.sitepoint.com/using-gnu-make-front-end-development-build-tool/


And on a related note, this is someone who advocates using npm scripts instead of grunt or gulp:

http://blog.keithcirkel.co.uk/why-we-should-stop-using-grunt/

http://blog.keithcirkel.co.uk/how-to-use-npm-as-a-build-tool/