Backbone + React – Data binding made easy – Nope - it's easy!



Backbone + React – Data binding made easy – Nope - it's easy!

0 0


backbone-react-presentation

reveal.js presentation of backbone + react

On Github ncherro / backbone-react-presentation

Backbone + React

Data binding made easy

React

A JavaScript library for building user interfaces
  • the 'V' in MVC
  • stateful
  • simple
  • fast
  • used in production on Facebook and Instagram

What makes React so fast?

“It uses a fast, internal mock DOM to perform diffs and computes the most efficient DOM mutation for you.”
  • when the state of a react component changes, react makes the change in it's "internal mock DOM" to determine what needs to change before it actually updates the DOM
  • DOM updates are batched, so they happen simultaneously
  • @vjeux's explanation of the diff algorithm

Wow, that sounds amazing.

It must be really ugly and difficult to use.

Nope - it's easy!

Let's render a list of posts

render the Posts component into #content

pass in a backbone collection we'll be able to refrence with @props.posts

  define ['react', 'ui/posts/index', 'collections/posts],
         (React, Posts, PostsCollection) ->

    React.renderComponent(
      Posts(
        posts: new PostsCollection
      ),
      document.getElementById('content')
    )
        

React.renderComponent() will probably be called in a backbone router action

Index

bind our custom @handleUpdate callback to the collection's add / remove / reset events, then call @props.posts.fetch()

when the collection changes, @handleUpdate changes our component's state to trigger render

  define ['react', 'ui/posts/show', 'ui/common/loading'],
         (React, Post, Loading) ->

    D = React.DOM

    React.createClass
      # event handlers
      handleUpdate: () ->
        # change the state to trigger re-rendering
        @setState { loading: false }

      # react
      getInitialState: ->
        loading: true

      componentWillMount: ->
        # update our state when the backbone collection changes
        @props.posts.on 'add remove reset', @handleUpdate, @

        # fetch posts!
        @props.posts.fetch()

      componentWillUnmount: ->
        # unbind event handlers
        @props.post.off null, null, @

      render: ->
        if @state.loading
          # render the Loading component
          Loading()
        else
          # loop through the collection, rendering a Post component for each model.
          D.div { className: 'posts' }, @props.posts.map (post) ->
            Post { post: post }

        
ui/posts/index.coffee

Show

The 'show' component just renders, displaying info from the @props.post backbone model using the backbone get method

  define ['react'], (React) ->

    D = React.DOM

    React.createClass

      render: ->
          D.div { className: 'post' }, [
            D.h3 {}, @props.post.get('title')
            D.div { dangerouslySetInnerHTML: { __html: @props.post.get('copy') }}
          ]
        
ui/posts/show.coffee

Lifecycle of a React component

Component specs and lifecycle are described here.

Every react component must define a render() method, but I ended up using these callbacks on every stateful component:

  • getInitialState()called before a component is mounted. sets the initial state of the component. changing the state later will trigger re-rendering
  • componentWillMount()called before a component is mounted. you have access to @props and can @setState without re-rendering. I typically use this to set up event listeners.
  • componentWillUnmount()called before a component is destroyed. this is a good place to unbind event listeners.

In summary

React gives us an efficient way to build and render stateful UI components

Using React + Backbone, we can:

set up a React component with a callback that triggers a simple state change, which triggers a re-render instantiate the component, passing in a Backbone model / collection use on() bind our component's callback to certain model / collection events use off() unbind events when the component unmounts

Resources

  • React referencesee links in the left sidebar REFERENCES section
  • Catalog of Backbone eventsa list of all possible backbone events, including arguments passed to the callback
  • Sample projectI set up this project to learn backbone and test data binding with reactit's a blog with Posts and Comments