我正在尝试理解骨干代码。我看了这个 http://addyosmani.com/blog/building-spas-jquerys-best-friends/
然后我打算改变这个
if (this._index === null){ $.ajax({ url: 'data/blog.json', dataType: 'json', data: {}, success: function(data) { ws._data = data; console.log(ws._data); ws._blogs = new BlogCollection(data.rows); console.log(ws._blogs); ws._index = new IndexView({model: ws._blogs}); Backbone.history.loadUrl(); } }); return this; } return this;
使用集合提取
if (this._index === null){ ws._data = new BlogCollection; ws._data.fetch({success: function(data){console.log(data.models[0].attributes);}}); //ws._blogs = new BlogCollection(ws._data.rows); //ws._index = new IndexView({model: ws._blogs}); Backbone.history.loadUrl(); }
使用此集合
var BlogCollection = Backbone.Collection.extend({ 型号:博客, url:'data / blog.json', parse:function(response){ 回复; }
当我从集合中读取响应时,它与使用jquery ajax的值相同。 但是当我在控制器中使用fetch时,为什么我必须访问data.models [0] .attributes);获得相同的数据返回。
这是我的json
{“page”:“1”,“total”:“5”,“records”:“25”,“rows”: [ { “标题”:“经典流行音乐”, “作者”:“迈克尔·杰克逊收藏”, “image”:“images / 1.jpg”, “tags”:[“xyz”,“abc”,“def”], “slug”:“经典流行音乐”, “url”:“http://www.localhost/news”, “介绍”:“你好测试”, “content”:“hello test,alfjldsajfldjsflja dljfldasjfa jfljdasfl jfldsjf jljdafl jl” }, { “标题”:“现代流行/ R& B”, “作者”:“Bruno Mars和其他人”, “image”:“images / 54.jpg”, “tags”:[“test”,“test2”,“test3”], “slug”:“modern-pop-rb”, “url”:“http://www.localhost/news”, “介绍”:“你好测试2”, “content”:“hello test,alfjldsajfldjsflja dljfldasjfa jfljdasfl jfldsjf jljdafl jl” } ]}
如何让fetch正常工作?
答案 0 :(得分:2)
扩展Backbone Collection时,应该定义一个parse
函数,该函数返回表示集合中包含的模型的行数组。
在您的情况下,它必须是数据数组,数组中的每个对象代表您的Blog
模型,因此您需要返回rows
属性:
var BlogCollection = Backbone.Collection.extend({
model: Blog,
url : 'data/blog.json',
parse: function(response){
return response.rows;
}
});
然后,如果您的模型具有parse
函数,它将获取数组中包含的每个对象的数据,以防您在设置模型属性之前需要对数据执行任何操作:
var Blog = Backbone.Model.extend({
//data will contain one of the items returned from the collection's 'parse' function.
parse: function(data){
return data;
}
});
这将确保Backbone集合将使用数据正确创建和填充集合中表示的模型。
您可能也希望在集合上公开其他元数据(page, total, records
),也许还有一个属性也是页面/总/记录的Backbone.Model
。