Muhammad Furqan
Muhammad Furqan

Reputation: 324

how to render view from object using backbonejs?

template code :

<script type="text/template" id="baseTemplate">
        <% collection.each(function() { %>
            <div>
                <%= collection %>
            </div>
        <% }); %>
</script>
<div id="baseContainer"></div>

and other code is :

//model
var PageModel = Backbone.Model.extend({
    defaults: {
        "id":null,
        "title":"",
        "content":""
    },
});
//collection
var PageCollection = Backbone.Collection.extend({
    defaults: {
        model: PageModel
    },
    model: PageModel,
    url: 'api/get_page/?id=6'
});
//view
var PageView = Backbone.View.extend({

    el: $('#baseContainer'),

    initialize: function () {
        this.collection = new PageCollection();
        this.collection.bind("reset", this.render, this);
        this.collection.bind("change", this.render, this);
        this.collection.fetch();
    },
    render: function () {

    var html = _.template($("#baseTemplate").html(), { collection: this.collection });
    this.$el.html(html);
    console.log(html);
    return this;
    }
});

 var page = new PageView();

problem is that its return and object how can i get values from object? api link is http://furqankhanzada.com/backbonejs/api/get_page/?id=6 and here you can see object in browser console http://furqankhanzada.com/backbonejs/ i need to get title, content , attachments -> images -> Gallery Large -> url (attachments using each() ).

Upvotes: 0

Views: 98

Answers (1)

Cyclone
Cyclone

Reputation: 1580

Not sure whether this is proper solution or not, but you can give it a try.

An alternative can be like,

var html = _.template($("#baseTemplate").html(), { models: this.collection.models });

Pass models instead of directly passing collection. And in the template you can do something like this,

<script type="text/template" id="baseTemplate">
  <% _.each(models, function(mdl) { %>
    <div>
      <%= mdl.get('title') %>
      <%= mdl.get('content') %>
      <% _.each(mdl.get('page').attachments, function(attachment) { %>
        <%= attachment.images["Gallery Large"].url %>
     <% }) %>  
   </div>
  <% }); %>
</script>
<div id="baseContainer"></div>

Please modify the markup as per your needs. But this solution is too specific to the problem :( :(

Upvotes: 1

Related Questions