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

问题描述:

我想一些数据加载到骨干网收集从本地JSON文件,使用这种非常基本的代码:从JSON文件将数据加载到Backbone集合中?

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

在控制台中陈述,AllStudents是空的。但是init.json肯定会被加载。它看起来像这样:

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

我在做什么错?

更新:我也尝试添加一个reset听者.fetch()拨打以上,但是这不点火之一:

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

中不会显示警报。

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

只有一个控制台声明甚至出现在第三fetch()通话,这是一个空的对象。

我现在绝对很困惑。我究竟做错了什么?

JSON文件被作为应用程序/ json提供,所以它与此无关。

+1

这是一个很好的问题。你应该使用http://jsonlint.com/来验证你的JSON – 2014-07-03 20:59:51

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

如果您分配了取到一个变量,你会得到的结果为好, 但随后它不是集合里面你想

+0

我不认为这是正确的 - '{add:true}'添加,而不是替换内容,但我想替换内容。 – Richard 2012-02-24 16:43:19

在javascript中的I/O操作几乎总是异步的,所以它也与Backbone一起使用。这意味着仅仅因为AllStudents.fetch已经返回,它还没有获取数据。所以当你点击你的console.log声明时,资源还没有被提取。你应该通过回调来fetch

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

或可选,使用jQuery的新承诺的功能(fetch会返回一个承诺):

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

嗯 - 那个控制台语句永远不会出现 - 好像成功永远不会被触发。 'init.json'文件正在被加载,但... – Richard 2012-02-24 16:40:54

fetch()方法返回一个 '成功' 的通知,已经说过,但这只是表示服务器请求已成功。 fetch()带回了一些JSON,但它仍然需要将其填充到集合中。

集合在内容更新时触发'重置'事件。这是当收集准备使用...

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

它看起来像你有你的第一次更新。我做的唯一不同的是把fetch()放在事件绑定的前面。

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

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

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

您应该看到非空集合对象。

你可以改变你的代码,看看成功和失败如下:

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

有关详细信息,因为这可能是在寻找的方式AJAX创建响应对象是个好主意。

+1

你是对的。这是正确的答案。这是正确的答案 – 2014-07-03 20:58:21