我正在尝试开发我的第一个骨干应用程序。一切看起来都不错,但是当我呈现视图并将一些html附加到$el时,页面中什么都不会呈现。Rest服务调用已完成,Backbone.Router.extend在$(document).ready(function () {});中声明,以确保创建DOM。调试我的javascript,el元素将在innerHTML属性中包含正确的值,但是当呈现整个页面时,该值不会出现在页面中。
我做错什么了?
我的视图代码:
window.ProductsListView = Backbone.View.extend({
id: 'tblProducts',
tagName: 'div',
initialize: function (options) {
this.model.on('reset', this.render, this);
},
render: function () {
// save a reference to the view object
var self = this;
// instantiate and render children
this.model.each(function (item) {
var itemView = new ProductListItemView({ model: item });
var elValue = itemView.render().el;
self.$el.append(elValue); // Here: the $el innerHTML is ok, but in the page it disappear. The id of element is div#tblProducts, so the element seems correct
});
return this;
}
});
window.ProductListItemView = Backbone.View.extend({
tagName: 'div',
template: _.template(
'<%= title %>'
),
initialize: function (options) {
this.model.on('change', this.render, this);
this.model.on('reset', this.render, this);
this.model.on('destroy', this.close, this);
},
render: function () {
$(this.el).html(this.template(this.model.toJSON()));
// $(this.el).html('aaaaaa'); // This neither works: it's not a template problem
return this;
},
close: function () {
$(this.el).unbind();
$(this.el).remove();
}
});在这里,我加载产品(在Backbone.Router.extend中)。这是正确执行的:
this.productsList = new ProductsCollection();
this.productsListView = new ProductsListView({ model: this.productsList });
this.productsList.fetch();这是我想要呈现的html元素:
<div id="tblProducts">
</div>提前谢谢你,
发布于 2013-03-06 08:46:38
从您已经发布的代码中,您实际上没有将您的ProductsListView插入到DOM中,也没有将它附加到现有的DOM元素。
我喜欢这样看,你有两种类型的视图:
通常,在列表的情况下,列表已经存在于页面上,并且它的项是动态添加的。我已经接受了您的代码,并在这弹琴中稍微对其进行了重构。您将看到ProductListView绑定到现有的ul,并且在将ProductItemView添加到集合时会动态地追加它们。
更新jsfiddle以演示Collection.reset
发布于 2013-03-06 08:36:11
如果呈现或未呈现el属性,则该属性存在于视图中。您不能在那里说它是可以的,因为如果没有传递任何元素(空div),主干将创建一个元素。
如果要呈现视图,应该确定元素的容器是什么?您有要附加视图的html吗?
尝试通过使用el调用视图来传递容器元素,如下所示
this.productsListView = new ProductsListView({ model: this.productsList, el : $("#container") });当然,您可以创建视图并在以后将其附加到DOM:
el: $("#someElementID") //grab an existing element
el.append(view.render().el);除非您将视图附加到某个地方,否则您的视图将不存在于dom中。
https://stackoverflow.com/questions/15242153
复制相似问题