我有一系列綁定到Backbone集合的閃存卡。一旦我收藏了,我創建了一個播放器模型的實例。骨幹 - 如何重構此代碼以防止鬼視圖?
然後用戶可以通過使用「下一步」和「上一個」按鈕的閃存卡,其餘導航。我第一次刺殺這個我認爲很簡單的事情是將閃卡片傳給這樣的球員。
不幸的是,這樣的設計導致了一個和上一個按鈕事件被每次被點擊的時間約束。因此,例如,在第一次點擊下一個按鈕之後,該事件開始不止一次發射。我讀了一些關於幽靈視圖的地方,但無法確切知道如何將下面的代碼分解成一個塊,這將幫助我防止幽靈視圖問題。
var flashCards = new Quiz.Collections.FlashCards({
id: this.model.get('card_set_id')
});
Quiz.player = new Quiz.Models.FlashCardPlayer({
collection: flashCards
})
Quiz.Models.FlashCardPlayer = Backbone.Model.extend({
defaults: {
'currentCardIndex': 0
},
initialize: function(){
this.collection = this.get('collection');
this.showCard();
},
showCard: function(){
var flashCard = this.collection.at(this.get('currentCardIndex'));
var cardView = new Quiz.Views.FlashCardPlayer({
model: flashCard
});
},
currentFlashCard: function(){
return this.get('currentCardIndex');
},
previousFlashCard: function(){
var currentFlashCardIndex = parseInt(this.get('currentCardIndex'), 10);
if(currentFlashCardIndex <= 0){
console.log("no less");
}
this.set({
'currentCardIndex': currentFlashCardIndex--
});
this.showCard();
},
nextFlashCard: function(){
var currentFlashCardIndex = parseInt(this.get('currentCardIndex'), 10);
if(currentFlashCardIndex >= this.collection.length){
console.log("no more");
}
currentFlashCardIndex = currentFlashCardIndex + 1;
this.set({
'currentCardIndex': currentFlashCardIndex
});
console.log(this.get('currentCardIndex'));
this.showCard();
}
});
Quiz.Views.FlashCardPlayer = Backbone.View.extend({
el: $('#cardSet'),
tagName: 'div',
_template: _.template($('#playerTemplate').html()),
initialize: function(){
console.log("in view flashcardplayer", this);
this.render();
},
events: {
'click #previous': 'getPreviousCard',
'click #next': 'getNextCard'
},
render: function(){
$(this.el).html(this._template(this.model.toJSON()));
return this;
},
getPreviousCard: function(){
this.close();
Quiz.player.previousFlashCard();
},
getNextCard: function(){
this.close();
Quiz.player.nextFlashCard();
}
});
script#playerTemplate(type="text/template")
<div id="state"></div>
<div id="previous">Previous</div>
<div id="card">
<h2><%= question %></h2>
<h3><%= answer %></h3>
</div>
<div id="next">Next</div>