4

更新: これは、私が取り組んでいたプロジェクトの動作デモです: http://www.newedenfaces.com

2 つのサムネイル (コレクション) を保持するPeopleViewと、各サムネイル自体 (モデル)のPersonViewの 2 つのビューがあります。

これは基本的に、2 つの画像を並べた Facemash のクローンです。1 人がゲームに勝った場合、別の 1 人がゲームに負けます。

wins countを更新するには、簡単です。これをPersonViewに追加するだけです。

// Model View
events: {
    'click img': 'winner'
},
winner: function() {
    this.model.set('wins', this.model.get('wins') + 1);
    this.model.save();
}

しかし、損失数を増やして他のモデルを更新するにはどうすればよいでしょうか? それとも、個々のモデルではなく、コレクション レベルでこの種のロジックを実行する必要がありますか?

アップデート

エレガントな解決策が見つかるまで、このハックを使用してこの問題を解決できました:

// Collection View
initialize: function() {
    this.collection.on('change:wins', this.updateLosses, this);
  },

  updateLosses: function(model) {
    var winnerIndex = this.collection.indexOf(model);
    var otherModel = this.collection.at(Math.abs(1 - winnerIndex));
    otherModel.set('losses', otherModel.get('losses') + 1);
    otherModel.save();
    this.render();
  },

私のPersonViewはまだ勝利数の更新を処理します。ただし、PeopleViewコレクション ビューは、勝利数が更新されたときにイベントをリッスンします。それが発生すると、そのモデルが取得され、そのインデックス位置が取得されます。私は 2 ビュー / 2 モデルしか持っていないので、もう一方のモデルは「敗者」だったに違いありません。を介して他のモデルのインデックスを取得し、Math.abs(1 - winnerIndex)必要なことはその損失数を更新することだけです。

:バックボーンの学習を始めたばかりなので、これを使用するのは初めてのプロジェクトです。これを行うためのより良い方法があることを本当に願っています。わかっている場合は、回答を投稿して、この質問を受け入れて閉じることができます。

4

2 に答える 2

3

@pvnarula の回答と同様に、Backbone のビルトインEventモジュールを使用して、モデル ビューがバインドされるイベント ディスパッチャーを作成できます。

// Define an event dispatcher/handler
var dispatcher = _.extend({}, Backbone.Events);

// Model View
initialize: {
    this.listenTo(dispatcher, 'game:over', this.updateCounts);
}

events: {
    'click img': 'winner'
},

winner: function() {
    // just trigger the custom event and let each view figure out how to respond.
    // also pass along the id of the winning model
    dispatcher.trigger('game:over', this.model.id)
},

updateCounts: function(winnerId) {
    if (this.model.id === winnerId) {
        this.model.set('wins', this.model.get('wins') + 1); 
    } else {
        this.model.set('losses', this.model.get('losses') + 1);
    }
    this.model.save();
}

また、バックボーンイベントの詳細については、この記事をチェックする価値があります。

于 2013-06-07T23:53:25.497 に答える
1

実際には、現在のビューから他のビューにアクセスし、それに応じて更新したいと考えています。残念ながら、独自のオブザーバー パターンを作成する必要があります。パブリッシュとサブスクライブを意味します。

var otherView = Backbone.View.extend({
   initialize : function(){
       observer.subscribe('your_custom_event');
   },
   your_custom_event : function(){
      //update the view and it's model
   }
});

winner: function() {
    this.model.set('wins', this.model.get('wins') + 1);
    this.model.save({wins: this.model.get('wins')});
    observer.publish('your_custom_event', arguments);
}

バックボーンと互換性のある非常に優れたパターンを Web から簡単に入手できます。

于 2013-06-07T20:44:39.330 に答える