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

时间:2023-01-24 10:04:48

I'm trying to load some data into a Backbone Collection from a local JSON file, using this very basic code:

我正在尝试使用这个非常基本的代码从本地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);

In the console statement, AllStudents is empty. But init.json is definitely being loaded. It looks like this:

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

[
  { text: "Amy", grade: 5 },
  { text: "Angeline", grade: 26 },
  { text: "Anna", grade: 55 }    
]

What am I doing wrong?

我究竟做错了什么?

UPDATE: I've also tried adding a reset listener above the .fetch() call, but that's not firing either:

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

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

No alert appears.

没有警报出现。

UPDATE 2: Trying this script (reproduced here in full):

更新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);
  });
});

Only one console statement even appears, in the third fetch() call, and it's an empty object.

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

I'm now absolutely baffled. What am I doing wrong?

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

The JSON file is being served as application/json, so it's nothing to do with that.

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

4 个解决方案

#1


18  

The attribute names and non-numeric attribute values in your JSON file must be double quoted (" ") . Single quotes or no-quotes produces errors and response object is not created that could be used to create the models and populate the collection.

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

So. If you change the json file content to :

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

[
  { "text": "Amy", grade: 5 },
  { "text": "Angeline", grade: 26 },
  { "text": "Anna", grade: 55 }    
]

you should see the non-empty collection object.

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

You can change your code to see both success and failure as below:

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

    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');
    }
  });

For more details, probably it will be a good idea to look in to the way ajax response objects are created.

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

#2


10  

I/O operations in javascript are almost always asynchronous, and so it is with Backbone as well. That means that just because AllStudents.fetch has returned, it hasn't fetched the data yet. So when you hit your console.log statement, the resources has not yet been fetched. You should pass a callback to fetch:

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

AllStudents.fetch({ url: "/init.json", success: function() {
    console.log(AllStudents);
}});

Or optionally, use the new promise feature in jQuery (fetch will return a promise):

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

AllStudents.fetch({ url: "/init.json" }).complete(function() {
    console.log(AllStudents);
});

#3


1  

fetch() returns a 'success' notification as already stated, but that just means that the server request was successful. fetch() brought back some JSON, but it still needs to stuff it into the collection.

fetch()返回如前所述的“成功”通知,但这只是意味着服务器请求成功。 fetch()带回了一些JSON,但它仍然需要将它填充到集合中。

The collection fires a 'reset' event when it's contents have been updated. That is when the collection is ready to use...

该集合在其内容更新后触发“重置”事件。那是集合准备好使用的时候......

AllStudents.bind('reset', function () { alert('AllStudents bind event fired.'); });

It looks like you had this in your first update. The only thing I did differently was to put fetch() in front of the event binding.

您的第一次更新看起来就像是这样。我做的唯一不同的事情是将fetch()放在事件绑定之前。

#4


0  

I think you need to add {add:true} to the options of fetch,

我想你需要在fetch的选项中添加{add:true},

if you assigned the fetch to a variable, you would get the result as well, but then its not inside the collection you wanted

如果你将fetch分配给变量,你也会获得结果,但是它不在你想要的集合中

#1


18  

The attribute names and non-numeric attribute values in your JSON file must be double quoted (" ") . Single quotes or no-quotes produces errors and response object is not created that could be used to create the models and populate the collection.

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

So. If you change the json file content to :

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

[
  { "text": "Amy", grade: 5 },
  { "text": "Angeline", grade: 26 },
  { "text": "Anna", grade: 55 }    
]

you should see the non-empty collection object.

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

You can change your code to see both success and failure as below:

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

    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');
    }
  });

For more details, probably it will be a good idea to look in to the way ajax response objects are created.

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

#2


10  

I/O operations in javascript are almost always asynchronous, and so it is with Backbone as well. That means that just because AllStudents.fetch has returned, it hasn't fetched the data yet. So when you hit your console.log statement, the resources has not yet been fetched. You should pass a callback to fetch:

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

AllStudents.fetch({ url: "/init.json", success: function() {
    console.log(AllStudents);
}});

Or optionally, use the new promise feature in jQuery (fetch will return a promise):

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

AllStudents.fetch({ url: "/init.json" }).complete(function() {
    console.log(AllStudents);
});

#3


1  

fetch() returns a 'success' notification as already stated, but that just means that the server request was successful. fetch() brought back some JSON, but it still needs to stuff it into the collection.

fetch()返回如前所述的“成功”通知,但这只是意味着服务器请求成功。 fetch()带回了一些JSON,但它仍然需要将它填充到集合中。

The collection fires a 'reset' event when it's contents have been updated. That is when the collection is ready to use...

该集合在其内容更新后触发“重置”事件。那是集合准备好使用的时候......

AllStudents.bind('reset', function () { alert('AllStudents bind event fired.'); });

It looks like you had this in your first update. The only thing I did differently was to put fetch() in front of the event binding.

您的第一次更新看起来就像是这样。我做的唯一不同的事情是将fetch()放在事件绑定之前。

#4


0  

I think you need to add {add:true} to the options of fetch,

我想你需要在fetch的选项中添加{add:true},

if you assigned the fetch to a variable, you would get the result as well, but then its not inside the collection you wanted

如果你将fetch分配给变量,你也会获得结果,但是它不在你想要的集合中