寻找使Backbone工作的绝对最小脚本。尝试拼凑各种教程和样本,但在查看工作时遇到问题。没什么好看的,我现在就在浏览器中使用原始json。只是一个基本的骨架,以帮助连接点和建立。我已尝试过以下各种变体:
(function ($) {
var model = Backbone.Model.extend({
idAttribute: 'custId'
});
var collection = Backbone.Collection.extend({
initialize: function(){
},
model: model,
url: '/cust'
});
var view = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'render'); // fixes loss of context for 'this' within methods
this.collection.bind("reset", this.render);
this.render();
},
el: $('#content'),
template: Handlebars.compile($("#contentTemplate").html()),
render: function(){
$(this.el).html( this.template(this.model.toJSON()));
},
tagName: "li"
});
var router = Backbone.Router.extend({
initialize: function(){
var newCollection = new collection;
newCollection.fetch();
},
route: {
"": "home"
},
home: function(){
this.view = new view({collection: newCollection});
$('#content').html(this.view.el);
}
});
var app = new router();
}(jQuery))
感谢名单。
答案 0 :(得分:1)
您滥用el
属性。 $('#content').html(this.view.el)
会导致复制$('#content')
元素本身(因为view.el等于$('#content')
)。
您应该尝试从视图对象中删除el
属性并让它自己生成。然后$('#content').html(this.view.el);
应该有用。
另一个可能的问题是你在li
元素中渲染整个集合 - 这就是你想要的吗?解决此问题的最佳方法是让集合中的每个模型代表li
代码,集合代表ul
代码。
其他问题:
view
元素正在接收集合,但您正在尝试呈现模型newCollection
Backbone.history.start()
以下是我将如何重写代码:
var model = Backbone.Model.extend({
idAttribute: 'custId'
});
var model_view = Backbone.View.extend({
template: Handlebars.compile($("#modelTemplate").html()),
tagName: 'li',
initialize: function() {
_.bindAll(this, 'render');
this.render();
this.on('change',this.render);
},
render: function() {
$(this.el).html( this.template(this.model.toJSON()) );
return this;
}
});
var collection = Backbone.Collection.extend({
initialize: function(){
},
model: model,
url: '/cust'
});
var collection_view = Backbone.View.extend({
tagName: "ul",
initialize: function(){
_.bindAll(this, 'render','renderModels');
this.render();
this.renderModels();
this.collection.bind("reset", this.render);
this.collection.bind("reset", this.renderModels);
},
render: function(){
// just create the 'ul' tag; we will populate it with model view elements; a collection template is no longer needed
return this;
},
renderModels: function() {
this.collection.each(function(obj){
var view = new model_view({
model: obj
});
$(this.el).append(view.el);
},this);
}
});
var router = Backbone.Router.extend({
initialize: function(){
this.newCollection = new collection();
this.newCollection.fetch();
},
route: {
"": "home"
},
home: function(){
this.view = new collection_view({collection: this.newCollection});
$('#content').html(this.view.el); // #content should not be a 'ul' tag, the 'ul' is generated by the collection_view
}
});
var app = new router();
Backbone.history.start();
确保相应地更新模板。
请原谅可能的错误,我无法测试代码,但我相信它指出了你应该使用的逻辑。
干杯!