我正在尝试开发我的第一个骨干应用程序。一切似乎都很好,但是当我渲染视图并将一些html附加到$el
时,页面中没有呈现任何内容。其余服务调用完成后,在$(document).ready(function () {});
内部声明Backbone.Router.extend
以确保创建DOM。调试我的javascript, el
元素在innerHTML属性中包含正确的值,但是当整个页面呈现时,该值不会出现在页面中。
My View code:
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>
提前致谢
从您发布的代码,您实际上并没有插入您的ProductsListView
到DOM或将其附加到现有的DOM元素。
我喜欢看它的方式是你有两种类型的视图:
- 根据从服务器返回的数据动态生成的
- 页面上已经存在的
通常在列表的情况下,列表已经存在于页面上,并且它的项是动态添加的。我已经采取了您的代码,并在本文中稍微重组了它。您将看到ProductListView
绑定到现有的ul
,而ProductItemView
在添加到集合中时是动态追加的。
更新jsfiddle以演示Collection.reset
无论是否呈现,el
属性都存在于视图中。你不能在这里说它是ok的,因为如果没有传递元素(空div), Backbone将创建一个元素。
如果你想渲染视图,你应该确定元素的容器是什么?你有想要附加视图的html吗?
尝试通过使用el
(如
this.productsListView = new ProductsListView({ model: this.productsList, el : $("#container") });
当然,你可以稍后创建视图并将其附加到DOM:
el: $("#someElementID") //grab an existing element
el.append(view.render().el);
你的视图不会存在于dom中,除非你把它附加在某个地方。