我不知道如何正确解释我的问题......
我想在不使用this.setElement()的情况下将两个视图追加到一个div容器。
父视图:
var app = app || {};
app.WidgetsView = Backbone.View.extend({
el: $('.widgets'),
initialize: function(options) {
self = this;
this.collection = options.collection;
this.render();
},
render: function() {
this.collection.each(function(item) {
this.renderViews(item)
}, this);
},
renderViews: function(item) {
this.View = new app.WidgetView({model: item});
this.$el.append(this.View.render().el);
},
});
子视图:
var app = app || {};
app.WidgetView = Backbone.View.extend({
className : 'widget six columns',
widgetTemplate : $('#widgetTemplate').html(),
initialize: function(options) {
var self = this;
this.model = options.model;
},
render: function() {
var modelIndexOfCollection = this.model.collection.indexOf(this.model);
if (!indexOfCollection & 1 === 1) {
$('.widgets').append('<div class="widgets-row"></div>');
this.setElement($('.widgets-row').last());
} else {
this.setElement($('.widgets-row').last());
}
this.$el.append(_.template(this.widgetTemplate)(this.model.toJSON()))
return this;
},
});
我希望我的HTML看起来像这样:
<div class="widgets">
<div class="widgets-row">
<div class="widget six columns"></div>
<div class="widget six columns"></div>
</div>
<div class="widgets-row">
<div class="widget six columns"></div>
<div class="widget six columns"></div>
</div>
<div class="widgets-row">
<div class="widget six columns"></div>
<div class="widget six columns"></div>
</div>
</div>
所以在伪代码中:
如果我的模型在我的集合中处于偶数位置,我想创建一个新的div并将此视图和下一个视图附加到新div。
谢谢
父:
var app = app || {};
app.WidgetsView = Backbone.View.extend({
el: $('.widgets'),
initialize: function(options) {
self = this;
this.collection = options.collection;
this.render();
},
render: function() {
this.collection.each(function(item) {
this.renderViews(item)
}, this);
},
renderViews: function(item) {
this.View = new app.WidgetView({model: item});
this.$el.append(this.View.render());
},
});
子:
var app = app || {};
app.WidgetView = Backbone.View.extend({
className : 'widget six columns',
widgetTemplate : $('#widgetTemplate').html(),
initialize: function(options) {
var self = this;
this.model = options.model;
},
render: function() {
var indexOfCollection = this.parentEl.collection.indexOf(this.model);
if (this.isEven(indexOfCollection)) {
$('.widgets').append('<div class="widgets-row row"></div>');
}
($('.widgets-row').last()).append(this.$el.append(_.template(this.widgetTemplate)(this.model.toJSON())))
return this;
},
isEven: function(value) {
if (value%2 == 0)
return true;
else
return false;
},
});