Last Updated: February 25, 2016
·
2.099K
· teito79

Backbone usage sample

This code can be executed into javascript console while visiting http://backbonejs.org

Create a model class.

var MyModelClass = Backbone.Model.extend({ });

Use the model with your data.

var myModelInstance = new MyModelClass({
    'name': 'John',
    'surname': 'Doe'
});

Create a view class, bind to an element of the DOM and bind model changes to render method.

var MyViewClass = Backbone.View.extend({

    el: '.container p:eq(1)',


    initialize: function () {
        this.model.bind('change', this.render, this);
    },
    render: function () {

        this.$el.html('<p>' + this.model.get('name') + ' ' + this.model.get('surname') + '</p>');
        _.bindAll(this);
        return this;
    }
});

Use the view by creating an instance with the model.

var myViewInstance = new MyViewClass({
    model: myModelInstance
});

Render the view.

myViewInstance.render();

Change an attribute of the model; this will trigger DOM elements refresh.

myViewInstance.model.set('name', 'Jack');

1 Response
Add your response

If only I had read this before...

over 1 year ago ·