Backbone.js-can't获取数据,或绑定到集合上的获取事件

Backbone.js - can't fetch data, or bind to the fetch event on collection?

本文关键字:获取 绑定 集合 事件 数据 js-can Backbone      更新时间:2023-09-26

我使用的是jQuery 1.7.1、Undercore 1.3.1和Backbone 0.9.1。这是我的主干代码,完整的:

$(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);
  }, failure: function() { 
      console.log('failure');
  }});
  AllStudents.fetch({ url: "/init.json" }).complete(function() {
      console.log(AllStudents);
  });
});

在第三个.fetch()调用中,甚至只出现一条console语句,然后它就是一个空对象。

我很困惑。我做错了什么?如何绑定到重置事件,并处理提取的数据?

这是JSON文件:

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

我已经检查了JSON文件是否被用作application/JSON,我还可以看到它被XHR请求提取了三次。

更新:这是我的HTML,全文:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<div class="container"></div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.1/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.1/backbone-min.js"></script>
<script src="/js/test.js"></script>
</body>
</html>

其他人能重现这个问题吗?

Backbone有一个很好的函数,它可以被称为parse的函数覆盖,一旦调用成功的获取,它就会获取获取的数据作为参数。您可以在加载JSON后使用它来处理JSON,例如:

window.Students = Backbone.Collection.extend({
    model: Student,
    parse: function(response) {
       console.log(response,response.results);
       return response.results;
  }
});