【发布时间】:2012-01-11 00:40:21
【问题描述】:
我有一个如下所示的 JSON 文件:
JSON:
{
"clefs": [
{"title": "..", "path": ".."},
... ,
{"title": "..", "path": ".."}
],
....
"rests": [
{"title": "..", "path": ".."},
... ,
{"title": "..", "path": ".."}
]
}
这是一个嵌套的 JSON,对吧?因此,我尝试将其转换为嵌套在 Backbone.js 中的模型/集合,如下所示:
Backbone.js:
window.initModel = Backbone.Model.extend({
defaults: {
"title": "",
"path": ""
}
});
window.CustomCollection = Backbone.Collection.extend({
model: initModel
});
window.Init = Backbone.Model.extend({
url : function(){
return "/api/data.json"
},
parse: function(response) {
clefs = new CustomCollection();
clefs.add(response.clefs);
this.set({clefs: clefs});
.....
rests = new CustomCollection();
rests.add(response.rests);
this.set({rests: rests});
}
});
现在我提出了一个模型并将其属性添加到我的集合中:谱号、...、休止符。
当我无法将我的 Collection 传递给 View 时!
我做了这个
路由器:
$(document).ready(function() {
var AppRouter = Backbone.Router.extend({
routes: {
"" : "init"
},
init: function(){
this.initial = new Init();
this.initialView = new InitView({model: this.initial});
this.initial.fetch();
}
});
var app = new AppRouter();
Backbone.history.start();
});
查看:
window.InitView = Backbone.View.extend({
initialize : function() {
this.model.bind("reset", this.render, this);//this.model.attributes send my 4 Collections Models back! But impossible to extract with "get" these Attributes
},
render : function() {
console.log("render");
}
});
现在的情况很糟糕!!我有一个带有属性(集合)的主干模型,但我无法提取这些属性,我尝试使用 JSON()、get、_.each、_.map 但没有成功!
我想要的是从模型名称的“初始”中提取我的收藏! this.initial.attributes 将我的收藏返回一个对象!但我不能将它们传递给视图!
更新 1:
现在 Model 已传递给视图,但我始终无法使用 get 访问他的属性或将他的属性发送给其他视图!渲染也不能被触发!!!
更新 2: 经过几天的头痛,我决定让它变得简单!
为什么?因为我现在只有 4 个集合:谱号、变音记号、音符和休止符
型号:
window.initModel = Backbone.Model.extend({
defaults: {
"title": "",
"path": ""
}
});
window.ClefsCollection = Backbone.Collection.extend({
model: initModel,
url: "/api/data.json",
parse: function(response){
return response.clefs;
}
});
...
and so on
路由器:
....
this.clefsColl = new ClefsCollection();
this.clefsColl.fetch();
this.clefsCollView = new ClefsView({collection: this.clefsColl});
....
【问题讨论】:
-
嗯,这里发生了几件事,但首先,你的 InitView 代码在哪里?
-
感谢 JayC!我用视图更新我的帖子!
-
很高兴你知道了。
标签: javascript backbone.js underscore.js