Rendering collection view in backbone.js

天大地大妈咪最大 提交于 2020-01-31 16:34:29

问题


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().


回答1:


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




回答2:


What you have asked is a generic question of how to use a collection to generate a view. Most of them are comfortable with generating a view with a model, but not with a collection. I followed the following tutorial Binding a collection to a view. Might be helpful for you also.



来源:https://stackoverflow.com/questions/15554769/rendering-collection-view-in-backbone-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!