2013-04-03 47 views
1

我試圖刪除舊的carView,並在單擊NEXT按鈕後添加下一個。如何使用if語句使用主幹來刪除和添加視圖

所有東西都出來了一個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() { 

    } 
}); 

回答

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

    } 
}); 
+0

謝謝!唯一的問題是,我不斷收到此錯誤:TypeError:'null'不是一個對象(評估'this.question_view.render') – user2238696

+0

謝謝! @Paul Hoenecke唯一的問題是,我一直得到這個錯誤:TypeError:'null'不是一個對象(評估'this.question_view.render') – user2238696

+0

@ user2238696呃...你從未將'this.question_view'設置爲任何東西。因爲它在您的原始文章中,所以我只是將它放在那裏。如果您不需要它,請將其移除。更新了答案。 –