Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering collection view in backbone.js

Tags:

backbone.js

I am having problems understanding how to render a collection in a view using a template. Here is my code:

<div id="mydiv"></div>

<script type="text/template" id="details">
<ul>
<% _.each(?, function(person)  { %>
<li><%= person.name %></li>
<% }); %>
</ul>
</script>

<script>
var m = Backbone.Model.extend();

var c = Backbone.Collection.extend({
        url: 'retrieve.php',
        model: m
 });

var v = Backbone.View.extend({
        el : $('#mydiv'),
        template : _.template($("#details").html()),
        initialize : function() {
        var coll = new c(); 
        coll.fetch({success: function(){alert(JSON.stringify(coll));} });              
        this.render();
        },
        render : function() {
        //what do I put here?
        return this;
       }
});

var view = new v();

I am confused about how to get the data returned from my php file into the template. What code do I need in the view and ._each? My php code is returning:

 [{"id":"1","name":"John","age":"5"},{"id":"2","name":"Jane","age":"2"}]

and I see this in the alert().

like image 500
user1884367 Avatar asked Dec 26 '22 07:12

user1884367


1 Answers

You should call your render function from the success handler as a collection.fetch returns result asynchronously (you can also bind render function to a collection reset event).

var v = Backbone.View.extend({
    el : '#mydiv',
    template : _.template($("#details").html()),
    initialize : function() {
      var self = this, 
          coll = new c(); 
      coll.fetch({ success: function(){ self.render() ; } });              
    },
    render : function() {
      // the persons will be "visible" in your template
      this.$el.html(this.template({ persons: this.coll.toJSON() }));
      return this;
    }
});

And in the template refer to the same persons object

<script type="text/template" id="details">
  <ul> 
    <% _.each(persons, function(person)  { %>
      <li><%= person.name %></li>
    <% }); %>
  </ul>
</script>

Update:

I've created the working fiddle, but I had to modify the original source code as I can't use your retrieve.php endpoint

like image 119
user20140268 Avatar answered Apr 10 '23 15:04

user20140268