JiboOne
JiboOne

Reputation: 1548

display fetched result of backbonejs model

I'm trying to show single model fetch result in html form

Here is my backbone.js part:

window.Category = Backbone.Model.extend({
    urlRoot : "../myWs/category/"
});

window.CategoryView = Backbone.View.extend({
    el : $('#category_details'),
    template : _.template($('#category-details').html()),
    initialize : function() {
        this.render();
    },
    render : function(eventName) {
        $(this.el).html(this.template(this.model.toJSON()));
        return this;
    }
});

var category = new Category({
    id : "067e6162-3b6f-4ae2-a171-240000000000"
});
var vategoryView = new CategoryView({
    model : category
});

category.fetch();

What I am doing is:

  1. Create a backbone model Category
  2. Creating a backbone view CategoryView
  3. Fetch data from rest web service which returns a JSON data object. Display the fetched data in the div "#category-details". On browsers , I can see that the "fetch()" method works, because I can see my JSON object returned

Here is HTML code:

<div id="category_details">details:</div>

<script type="text/template" id="category-details">
<label>Id:</label>
<input id="id" name="id" type="text" disabled />

<label>Name:</label>
<input type="text" id="name" name="name" value="<%= name %>"/>
 </script>

The problem is that data is not shown in html. How can I display data in html?

Upvotes: 1

Views: 1558

Answers (1)

nikoshr
nikoshr

Reputation: 33344

Your view doesn't handle the changes on the model, which implies that the view is not re-rendered when model.fetch completes.

Try binding the change event from the model:

window.CategoryView = Backbone.View.extend({
    el : $('#category_details'),
    template : _.template($('#category-details').html()),
    initialize : function() {
        this.render();
        this.model.on('change', this.render, this);
    },
    render : function(eventName) {
        $(this.el).html(this.template(this.model.toJSON()));
        return this;
    }
});

And a demo http://jsfiddle.net/Hzm5Y/

Note that Underscore dislikes being asked to render undefined variables, you probably should add defaults to your model:

window.Category = Backbone.Model.extend({
    urlRoot : "../myWs/category/",
    defaults: {
        name: ''
    }
});

Upvotes: 2

Related Questions