我正在使用Backbone开发一个新的应用程序,但还没有编写后端API,所以我正在尝试使用项目本地的JSON数据文件。我将它的位置设置为urlRoot,并且能够获取它并接收回jqXHR对象。但是,我不确定如何与responseText交互(根据对象的console.log输出,假设这就是我需要的)。
这是我发现的最接近我的问题,但它不是以最终答案结束的:backbone model is only returning and object, or JSON {readyState : 1}
var JobListings = Backbone.Model.extend({
urlRoot: 'scripts/app/data/listings.json'
});
// Instantiate the model
var jobListings = new JobListings();
console.log(jobListings.fetch()); // Returns jqXHR object
console.log(jobListings.attributes); // Returns empty object如何获取我的JSON数据?另外,它应该在模型中,而不是集合中,对吗?对于基于其他开发人员使用的集合的角色,我有点模糊。我认为模型包含数据,而集合是模型的集合。
我的目标是为数据构建两个模型。一个接收需要清理的脏JSON,第二个接收我输出的干净数据,以供应用程序使用。任何帮助都是非常感谢的。
编辑:
我的JSON的一小段。我仍然不知道如何获取我的数据。我确信我不必事先进入视图来查看我的数据。
[
{
"jobId": "1",
"applyUrl": "http://google.com",
"title": "President of the World",
"trackingCode": "1",
"jobDescription": "Stuff",
"requiredSkills": "Stuff",
"requiredExperience": [],
"postingDate": "2013-07-12T11:07:50Z",
"jobLocation": {
"countryCode": "US",
"region": "California",
"municipality": "Santa Monica"
},
"category": "Life",
"businessUnit": [],
"positionType": "Full-Time"
}
]发布于 2013-07-19 05:15:46
'Backbone.Model'包含数据
'Backbone.Collection'是一组模型。就像你可以在下面这样定义它:
var Library = Backbone.Collection.extend({
model: Book
});您通常不会直接使用jqXHR。数据获取完成后,您可以使用get操作逐个字段(或逐个属性)访问数据:
note.get("title")您可以使用set操作编辑数据:
note.set({title: "March 20", content: "In his eyes she eclipses..."});
book.set("title", "A Scandal in Bohemia");您可以使用toJSON操作返回数据的副本(称为属性
此外,Backbone还将使用hasChanged跟踪数据是否脏
发布于 2013-07-19 19:34:01
看一下您的代码,JobListing将是一个包含工作列表数据的模型。JobListings将是所有JobListing模型的集合:
var JobListing = Backbone.Model.extend();
var JobListings = Backbone.Collection.extend({,
model: JobListing,
url: 'scripts/app/data/listings.json',
parse: function(data) {
// Not sure about your json structure, but you could do the following
// Do your cleanup here
return data.joblistings;
}
});
// Instantiate the collection
var jobListings = new JobListings();
var req = jobListings.fetch();
req.done(function() {
// contains all job listings
console.log(jobListings.models);
});https://stackoverflow.com/questions/17733494
复制相似问题