从JSON文件加载数据到Backbone集合?

Ric*_*ard 17 javascript json backbone.js

我正在尝试使用这个非常基本的代码从本地JSON文件将一些数据加载到Backbone Collection中:

  window.Student = Backbone.Model.extend({
  });
  window.Students = Backbone.Collection.extend({
    model: Student, 
  });
  window.AllStudents = new Students();
  AllStudents.fetch({ url: "/init.json"});
  console.log('AllStudents', AllStudents);
Run Code Online (Sandbox Code Playgroud)

在控制台语句中,AllStudents为空.但init.json肯定是被装载.它看起来像这样:

[
  { text: "Amy", grade: 5 },
  { text: "Angeline", grade: 26 },
  { text: "Anna", grade: 55 }    
]
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

更新:我也尝试reset.fetch()调用之上添加一个监听器,但是它没有触发:

AllStudents.bind("reset", function() {
  alert('hello world');
});
AllStudents.fetch({ url: "/init.json"});
Run Code Online (Sandbox Code Playgroud)

没有警报出现.

更新2:尝试此脚本(完整转载):

$(function(){
  window.Student = Backbone.Model.extend({
  });
  window.Students = Backbone.Collection.extend({
    model: Student, 
  });
  window.AllStudents = new Students();
  AllStudents.url = "/init.json";
  AllStudents.bind('reset', function() { 
      console.log('hello world');  
  }); 
  AllStudents.fetch();
  AllStudents.fetch({ url: "/init.json", success: function() {
      console.log(AllStudents);
  }});
  AllStudents.fetch({ url: "/init.json" }).complete(function() {
      console.log(AllStudents);
  });
});
Run Code Online (Sandbox Code Playgroud)

在第三次fetch()调用中,甚至只显示一个控制台语句,它是一个空对象.

我现在非常困惑.我究竟做错了什么?

JSON文件作为application/json提供,因此它与此无关.

Pra*_*aym 18

JSON文件中的属性名称和非数字属性值必须双引号("").单引号或无引号会产生错误,并且不会创建可用于创建模型和填充集合的响应对象.

所以.如果您将json文件内容更改为:

[
  { "text": "Amy", grade: 5 },
  { "text": "Angeline", grade: 26 },
  { "text": "Anna", grade: 55 }    
]
Run Code Online (Sandbox Code Playgroud)

你应该看到非空的集合对象.

您可以更改代码以查看成功和失败,如下所示:

    AllStudents.fetch({ 
    url: "/init.json", 
    success: function() {
          console.log("JSON file load was successful", AllStudents);
      },
    error: function(){
       console.log('There was some error in loading and processing the JSON file');
    }
  });
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看ajax响应对象的创建方式可能是个好主意.


Lin*_*iel 10

javascript中的I/O操作几乎总是异步的,因此它也适用于Backbone.这意味着只是因为AllStudents.fetch已经返回,它还没有获取数据.因此,当您点击console.log语句时,尚未获取资源.您应该将回调传递给fetch:

AllStudents.fetch({ url: "/init.json", success: function() {
    console.log(AllStudents);
}});
Run Code Online (Sandbox Code Playgroud)

或者,可选地,在jQuery中使用新的promise功能(fetch将返回一个promise):

AllStudents.fetch({ url: "/init.json" }).complete(function() {
    console.log(AllStudents);
});
Run Code Online (Sandbox Code Playgroud)


min*_*dia 0

我认为你需要添加{add:true}到 fetch 的选项,

如果将获取分配给变量,您也会得到结果,但它不在您想要的集合内