1

单击按钮后,我正在尝试删除旧的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 () { 

    } 
});
4

1 回答 1

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

    } 
});
于 2013-04-03T04:19:17.610 回答