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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/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,可能重复: 在我下面的函数中,控制台显示数据,但没有任何内容附加到body标记,任何人都会发现问题 我的json: [ {name:'student4'}, {name:'student5'}, {name:'student6'} ] 代码: (function($){ var model = Backbone.Model.extend({ defaults:{ name:'default name' } }); var collect

可能重复:

在我下面的函数中,控制台显示数据,但没有任何内容附加到body标记,任何人都会发现问题

我的json:

[
    {name:'student4'},
    {name:'student5'},
    {name:'student6'}
]
代码:

    (function($){   
var model = Backbone.Model.extend({
  defaults:{
    name:'default name'
  }
});

var collection = Backbone.Collection.extend({
  model:model,
  url: 'data/names.json'
});



var itemViews = Backbone.View.extend({
  tagname:'li',
  render:function(){
    this.$el.html(this.model.get('name'));
    return this;
  }  
})

var view = Backbone.View.extend({
  el: $("#contacts"),
  initialize:function(){
    this.collection = new collection();
    this.collection.on("reset", this.render, this);
    this.collection.fetch();
  },
  render:function(){
    var that = this;
    _.each(this.collection.models, function(item){
      that.renderName(item);
    })
  },
  renderName:function(item){
    var itemView = new itemViews({model:item});
    this.$el.append(itemView.render().el); //nothing rendering
  }
});


var stView = new view();

})(jQuery)

问题似乎出现在以下两行:

this.collection.fetch(); //it seems it's not fetching;
this.render();  
Collection.fetch
是一个异步操作。当您呈现视图时,请求尚未返回,因此您的集合为空。尝试将呈现方法绑定到集合
reset
事件:

collection.on("reset", this.render, this);
this.collection.fetch();

您在哪个位置进行console.log收集?恐怕要解析到集合中的JSON数据必须像
[{name:'student4'},{name:'student5'},…]
一样,没有额外的
{name:[]}
我尝试过,运气不好。特别是在每种情况下,我都没有看到任何东西,但是如果我只是控制集合,它会显示数据,如果请求数据也显示对象,我会尝试执行.fetch().then(function(){that.render()});我更新了,但渲染功能根本没有called@3gwebtrain,稍微改变了我的回答。以前的版本也应该可以工作,但是有一些复杂的问题可能导致它失败。
reset
事件更简单。我更新了编码,仍然无法工作。让我为您的视图再次更新孔代码。如果可能的话,你能让我听一听吗?html可能有问题。查看是否有带有
id=“contacts”
的元素。