我正在尝试删除旧的carView
,并在点击NEXT
按钮后添加下一个window.CarContainerView = Backbone.View.extend({
el: $('#car-container'),
template:_.template($('#tpl-car-container').html()),
initialize:function () {
_.bindAll(this, 'clickNext');
this.car_number = 0;
this.car_model = this.model.get('carCollection').models[this.question_number];
this.question_view = null;
},
render:function () {
$(this.el).html(this.template());
this.car_view = new CarView({el: $(this.el).find('#car'), model: this.car_model});
this.question_view.render();
$('#next').bind('click', this.clickNext);
return this;
},
createNewCar: function () {
//build
console.log('createNewCar');
if(condition) {
//if the next button is pressed, clear screen and add new screen
}
},
clickNext: function () {
this.car_number++;
console.log(this.car_number);
createNewCar();
},
clickPrevious: function () {
}
});
。
所有内容都来自JSON文件并正在递增,但我想查看也会更改。
以下是我的观点代码:
{{1}}
答案 0 :(得分:2)
评论解释了这些变化。基本上,每次都要创建一个新的CarView。并且不要将el
传递给视图,否则当您调用remove
时该元素将会消失。相反,每次都将新视图渲染为#car
。
window.CarContainerView = Backbone.View.extend({
el: $('#car-container'),
template:_.template($('#tpl-car-container').html()),
// use events hash instead of directly using jquery.
events: {
'click #next': 'clickNext'
},
initialize:function () {
// no need to use bindAll since using events hash
// binds the context of clickNext to this view already.
this.car_number = 0;
},
render:function () {
// use this.$el instead.
this.$el.html(this.template());
this.createNewCar();
return this;
},
createNewCar: function () {
if(this.car_view){
// cleanup old view.
this.car_view.remove();
}
// do some bounds checking here, or in clickNext... or both!
var car_model = this.model.get('carCollection').models[this.car_number];
// create a new view for the new car.
this.car_view = new CarView({model: car_model});
// render into #car instead of passing `el` into the view.
// let Backbone generate a div for the view, you dont need to
// set an `el` in the CarView either.
this.$('#car').html(this.car_view.render().el);
},
clickNext: function () {
this.car_number++;
this.createNewCar();
},
clickPrevious: function () {
}
});