Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Using React with Backbone Models

React allows you to ren­der views in a very high per­for­mance way. The best thing about react is that it also plays fair with other frame­works like back­bone for imple­ment­ing the other lay­ers. For exam­ple, one of the sim­plest use case would be to use react’s view com­po­nents to ren­der back­bone models.

NOTE: The entire source code of this project is avail­able at github on the react-backbone-model branch of our react-webpack-setup project. If you are inclined to learn how to setup react with web­pack you can check­out another arti­cle that cov­ers the topic in detail.

If it sounds com­pli­cated at first, its really not. If I were to sum it up one line, this is what I would say — Just call the component’s force­Up­date() on the ‘change’ event in a back­bone model.

Lets put that line into some con­text and see how we can achieve that.


Since we are going to use the react-webpack-setup project, we will be con­ve­niently using npm and require in our front end code.


Pack­ages
First lets install back­bone model. We dont need the whole of back­bone so we will just install the model package.

npm install backbone-model --save

The Model
We will cre­ate a very sim­ple back­bone model called Note which con­tains a sigle attribute called details.

models/Note.js

var Model = require('backbone-model').Model,
    Note = Model.extend({
      details: ""
    });

module.exports = Note;

The Com­po­nents
What fol­lows next is the code for 2 react com­po­nents. The first com­po­nent Page is a top level page com­po­nent that man­ages all the other com­po­nents on the page. The sec­ond com­po­nent Note is the com­po­nent that will ren­der our Note model. It sim­ply dis­plays a textarea called the ‘edi­tor’ which, of course, you can edit. Upon edit­ing, we want it to update the model’s ‘details’ attribute. This value will be auto­mat­i­cally dis­played in another div on the page called as the ‘viewer’ and will be italicized.

components/notes/Page.jsx

/**
 * @jsx React.DOM
 */

var React = require('react'),
    NoteModel = require('../../models/Note'),
    Note = require('./Note'),
    note = new NoteModel();

var Page = React.createClass({

    render: function() {

        return (
            <div>
                <Note model={note}/>
            </div>
        );

    }

});

module.exports = Page;

components/notes/Note.jsx

/**
 * @jsx React.DOM
 */

var React = require('react'),
    ModelUpdateMixin = require('../../mixins/ModelUpdateMixin');

var Note = React.createClass({

    mixins:[ModelUpdateMixin],

    render: function() {

        var p = this.props;

        return (
            <div>

                <div className="editor">
                    <h5>Notes Editor</h5>
                    <textarea rows="3" cols="50"
                        ref="noteDetails"
                        placeholder="Enter some notes"
                        onChange={this._onDetailChange}>
                        {p.model.get('details')}
                    </textarea>
                </div>

                <div className="viewer">
                    <h5>Viewer</h5>
                    <i>{p.model.get('details')}</i>
                </div>

            </div>
        );

    },

    _onDetailChange: function(e){
        var p = this.props,
            noteDetails = this.refs.noteDetails.getDOMNode().value;

        p.model.set('details', noteDetails);
    }

});

module.exports = Note;

The above code does two sim­ple things, it renders the detail attribute of the model once in a textarea and once in a div. The textarea can be edited. We lis­ten to the onChange event and sim­ply set the value on the model equal to the value on the textfield. Nor­mally this would not let you edit the textfield. The rea­son why you can edit the textfield is because of the Mixin that is defined at the top of this class at the lines that read mixins:[ModelUpdateMixin].


The Mixin
This is the glue object that causes the view to update when the model updates. React lets you define mix­ins that allow you to aug­ment a component’s life­cy­cle meth­ods. A mixin that then be used in a react com­po­nent, as seen in the code for Note.jsx above. What you see below is the Mod­elUp­dateMixin, which is noth­ing but an object that aug­ments two of React’s component’s life­cy­cle meth­ods to whichever com­po­nent it is included– the com­po­nen­tWill­Mount and the com­po­nen­tWillUn­mount. The code below is pretty sim­ple — on com­po­nent mount, just sub­scribe to the component’s model’s change event and force a re-render of the view when a change is trig­gered by the model. You could add safety checks in your own code just in case model is unde­fined, but for the sake of this exam­ple, this should suf­fice. On com­po­nent unmount, sim­ply unsub­scribe from the change event.

ModelUpdateMixin.js

var ModelUpdateMixin = {

    componentWillMount: function(){
        this.props.model.on("change", (function() {
          this.forceUpdate();
        }.bind(this)));
    },

    componentWillUnmount: function(){
        this.props.model.off("change");
    }

};

module.exports = ModelUpdateMixin;

That said, you are now ready for show­time. To see the work­ing exam­ple for your­self, down­load the branch — react-backbone-model from our repos­i­tory and run the fol­low­ing com­mands on your terminal.

sudo npm install -g grunt-cli
npm install
npm run dev

Then open localhost:3000/notes.html in your browser and have some fun.


Ryan Sukale

Ryan is a UX engineer living in San Francisco, California.

You may also like...