Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在backbone.js中呈现集合视图_Backbone.js - Fatal编程技术网

在backbone.js中呈现集合视图

在backbone.js中呈现集合视图,backbone.js,Backbone.js,我在理解如何使用模板在视图中呈现集合时遇到问题。这是我的密码: <div id="mydiv"></div> <script type="text/template" id="details"> <ul> <% _.each(?, function(person) { %> <li><%= person.name %></li> <% }); %> </ul> </s

我在理解如何使用模板在视图中呈现集合时遇到问题。这是我的密码:

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

我在alert()中看到了这一点。

您所问的是如何使用集合生成视图的一般问题。他们中的大多数人都习惯于使用模型生成视图,但不习惯使用集合。我遵循了下面的教程。可能对您也有帮助。

您应该从
success
处理程序中调用
render
函数作为
集合。fetch
异步返回结果(您也可以
render
函数作为集合
重置
事件)

在模板中引用相同的
人员
对象

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

更新:


我已经创建了工作,但是我不得不修改原始源代码,因为我不能使用您的
retrieve.php
endpoint

Hmm!我遵循逻辑,但由于某种原因,我无法让它工作。我运行代码时什么都看不到。有什么想法吗?太好了。感谢您的帮助这是一种糟糕的方法,因为如果您的任何模型发生更改,您需要重新渲染整个集合,以在视图中反映该更改。@Jaseem Hi。如果你认为这是一个糟糕的方法,那么你能分享一些你认为是更好的方法吗?另外,我对backbone.js还是新手
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;
    }
});
<script type="text/template" id="details">
  <ul> 
    <% _.each(persons, function(person)  { %>
      <li><%= person.name %></li>
    <% }); %>
  </ul>
</script>