0

私はバックボーンコレクションに結びついているフラッシュカードのコレクションを持っています。コレクションを取得したら、プレーヤーモデルのインスタンスを作成します。バックボーン - ゴーストビューを防ぐためにこのコードをどのようにリファクタリングするのですか?

次に、ユーザーは、「次の」および「前の」ボタンを使用して残りのフラッシュカードをナビゲートすることができます。私が思ったこれを行う最初の刺し傷は、このようなプレーヤーにflashCardsを渡すことでした。

このデザインでは、次回と前のボタンイベントがクリックされるたびにバインドされています。たとえば、次のボタンを最初にクリックした後、イベントは2回以上発射されます。私はゴーストビューのどこかを読んでいますが、以下のコードをどのようにしてゴーストビューの問題を防ぐのに役立つチャンクにするかを正確に理解できませんでした。

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

});

});

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> 

答えて

2

新しいカードを表示するたびに、Quiz.Views.FlashCardPlayerの新しいインスタンスが作成されます。これらのインスタンスはそれぞれ独自のイベント処理を行うため、各インスタンスは同じ#nextおよび#previous要素にバインドされています。

私はここで概念的な問題のカップルがあると思います。

  • あなたが唯一の次/前の要素にイベントをバインドする必要があり1つのFlashCardPlayerビューを、必要とします。 1つのカードしか表示されない別のFlashCardビューが必要です。プレイヤーは、次の/前のボタンが押されると、そのビューを入れ替えることができます。一般的な規則として、idの要素がある場合は、1回のビューインスタンスでレンダリングしてバインドする必要があります。そうしないと、今までと同じ問題が発生します。

  • FlashCardPlayerモデルにあまりにも多くのものを詰め込もうとしています。原則として、モデルはデータを表示するために使用されるビューではなく、そのデータについてのみ知っている必要があります(モデルの1つがさまざまなビューで表示される必要があるためです)。モデルのnextFlashCard()previousFlashCard()メソッドをモデルに持たせても構いませんが、これはまだコレクションに関するデータを格納する領域ですが、プレゼンテーションロジックを扱うので、showCard()メソッドは実際にビュー領域に移動しています。もっと良い考えは、モデルのビューイベントにバインドしてthis.model.get('currentCardIndex'))(または新しいgetCurrentCard()メソッド)を使用して、新しいカードの表示を処理することです。

関連する問題