Search code examples
javascriptbackbone.js

Unable to get the Backbone View working for a simple example


I am trying to write a simple example using Backbone.js for study. Some how nothing gets printed in the browser. Need a little help here. The code is given below.

Html:

<div id="container">
    <ul id="person-list">
    </ul>
</div>

Models

var Person = Backbone.Model.extend({
    defaults: {
        id: 0,
        name: ''
    }
});

var PersonStore = Backbone.Collection.extend({
    model: Person,
    url: 'api/person', //currently not using
    initialize: function () {
        console.log("Store initialize");
    }
});

Views

var PersonView = Backbone.View.extend({
    tagName: 'li',
    initialize: function () {
        _.bindAll(this, "render");
    },
    render: function () {
        $(this.el).append(this.model.name) //model.name shows undefined here
        return this;
    }
});

var PersonListView = Backbone.View.extend({
    el: $('#person-list'),
    tagName:'ul',
    initialize: function () {
        _.bindAll(this, "render");
        this.render();
    },
    render: function () {
        self = this;
        this.collection.each(function (person) { //name property undefined here on person
            var personView = new PersonView({ model: person });
            $(self.el).append(personView.render().el);
        });
    }
});

Sample Run

var persons = new PersonStore([
     new Person({id:1, name: "Person 1"}),
     new Person({ id: 2, name: "Person 2" }),
]);
new PersonListView({ collection: persons });

The above setup prints nothing(blank) on screen. I have struggled now for some time and need a little help here as to why the two Person's name does not get displayed in the browser.


Solution

  • To make your code work you have to replace

    this.$el.append(this.model.name) 
    

    with

    this.$el.append(this.model.get('name'))
    

    Always use method .get() to access model properties.

    Also i highly recommend you use templates for rendering views. This approach let you write .render() implementation once and will be no need to change it if you need visual changes, you can make in template