如何使用if语句删除和添加视图

How to remove and add a view using an if statement using backbone

本文关键字:添加 视图 删除 语句 何使用 if      更新时间:2023-09-26

我试图删除我的旧carView,并添加下一个一旦点击NEXT按钮。

所有内容都来自JSON文件,并且正确地递增,但我希望查看也可以更改。

下面是我的视图的代码:

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 () { 
    } 
});

注释解释了这些变化。基本上,每次都创建一个新的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 () { 
    } 
});