我是Backbone的新手。当我尝试同时渲染父视图和子视图时,只渲染了父视图!我想知道为什么会发生这种情况以及实现这一目标的其他方法是什么?
childView.js:
var ChildView = Backbone.View.extend({
template: _.template($('#foo').html()),
initialize: function() {
},
render: function() {
$(this.el).html(this.template({}));
return this;
}
});
parentView.js:
var ParentView = Backbone.View.extend({
el: $('body'),
initialize: function() {
this.childView = new ChildView();
this.render();
},
render: function() {
var self = this;
$.get('templates/parentView.html', function(data) {
template = _.template(data, {});
self.$el.html(template);
}, 'html');
$('#main').html(this.childView.render().el);
},
});
var parentView = new ParentView();
parentView.html:
<header>
<h1>This is header</h1>
</header>
<main id="main">
</main>
<footer>
<p>This is footer</p>
</footer>
答案 0 :(得分:2)
可以做出很多改进,这里有一些改进:
this.$el
,或者对作用域jQuery搜索使用this.$()
。el
接受字符串或DOM元素,而不是jQuery对象。render
应该是幂等且快速的,不要每次都获取模板。.html()
功能比.empty().append()
重一点。.get()
(成功)回调。.setElement()
。var ChildView = Backbone.View.extend({
template: _.template($('#foo').html()),
render: function() {
this.$el.empty().append(this.template({}));
return this;
}
});
var ParentView = Backbone.View.extend({
el: 'body',
initialize: function() {
this.childView = new ChildView();
$.get({
url: 'templates/parentView.html',
success: this.onTemplateLoad,
context: this,
dataType: 'html'
});
},
render: function() {
this.$el.empty().append(this.template({ /** data */ }));
this.childView.setElement(this.$('#main'));
return this;
},
onTemplateLoad: function(data) {
this.template = _.template(data, {});
this.render();
}
});
var parentView = new ParentView();
答案 1 :(得分:1)
在父视图[{:name=>"something1", :brokerage=>"some broker1", :avg_price=>100, :avg_rating=>1},
{:name=>"something4", :brokerage=>"some broker2", :avg_price=>100, :avg_rating=>1},
{:name=>"something7", :brokerage=>"some broker3", :avg_price=>100, :avg_rating=>1},
{:name=>"something10", :brokerage=>"some broker4", :avg_price=>100, :avg_rating=>1}]
函数中,子视图render
被分配给el
但是在那时它不在DOM上,因为没有附加父视图$('#main')
对于DOM,您可以进行以下更改以将子视图html分配给父视图el
。
el
this.$el.find('#main').html(this.childView.render().el);
$(body).html(this.$el);
搜索DOM上的元素,$("#main")
搜索this.$el.find("#main")
元素后代中的元素。