我是Backbone的新手,正在努力将我的脑袋包裹起来。 让我试着解释一下我想做什么: 我正在制作一个具有SVG元素的应用程序,其中包含SVG组。这些组将嵌套在彼此之内:
http://i.stack.imgur.com/yAkTE.png
我试图使用Backbone为每个组创建模型和视图。并使用集合将子组嵌套在这些组中。
到目前为止,我已经使用div而不是任何SVG编写了以下内容,以便在我实现这一方面之前使逻辑工作。但我想我的想法可能只是在某个地方完全不知所措,任何帮助都会非常感激。
我知道在Backbone中有关于嵌套等的类似线程,但我还没有找到任何帮助。
你可以看到我到目前为止所写的JSFiddle:http://jsfiddle.net/ZqMeV/ 这是迄今为止的代码:
(function ($) {
var Cell = Backbone.Model.extend({
initialize: function(){
this.children = new CellCollection();
}
});
var CellCollection = Backbone.Collection.extend({
model: Cell
});
var CellView = Backbone.View.extend({
tagName: "div",
initialize: function(){
if(this.model.children.models.length > 0){
_.each(this.model.children.models, function(child){
console.log(child);
var cell = new CellView({
model: child
});
$(this.el).append(cell.el);
});
} else {
$(this.el).html('cell');
}
}
});
var Canvas = Backbone.Model.extend({
initialize: function(){
//below is just for testing purposes
this.content = new Cell();
var c = new Cell();
var d = new Cell();
var e = new Cell();
this.content.children.add(c);
this.content.children.add(d);
d.children.add(e);
}
});
var CanvasView = Backbone.View.extend({
el: $("#canvas"),
tagName: "div",
initialize: function(){
this.cellView = new CellView({
model: this.model.content
});
$(this.el).append(this.cellView.el);
}
});
var canvas = new Canvas();
var canvasView = new CanvasView({
model: canvas
});
} (jQuery));
由于
答案 0 :(得分:0)
你有很大的背景问题:
_.each(this.model.children.models, function(child){
console.log(child);
var cell = new CellView({
model: child
});
$(this.el).append(cell.el);
});
此处您的this
内部已发生变化。您可以通过以下方式替换它:
var self = this;
this.model.children.each(function(child) {
var cell = new CellView({
model: child
});
$(self.el).append(cell.el);
});
哦,顺便说一句,Backbone的Collections代理了许多下划线方法,所以我冒昧地改变了你的每一个。您也可以this.model.children.models.length
替换this.model.children.length
。学习使用集合,而不仅仅是内部的数组:)