3

ItemView をメニューにレンダリングする Marionette CollectionView があり、<select>各 ItemView は<option>. 私の質問は、CollectionView で「変更」イベントを呼び出したとき (ユーザーがオプションを選択したことを意味します)、<option>ItemView から選択したモデルを取得するにはどうすればよいですか?

var singleView = Marionette.ItemView.extend({
        template: '#optionTemplate',
        tagName: 'option'
    });

var listView = Marionette.CollectionView.extend({
        itemView: singleView,
        tagName: 'select',
        id: 'my-selector',
        events: {
            'change': 'optionSelected'
        },
        optionSelected: function() {
          // I need to get the model from within this function

        }
    });
4

3 に答える 3

5

最もクリーンな方法はoption、対応するモデルの ID を値としてタグをレンダリングすることです: <option value="42">Forty Two</option>. 次に、変更時にその値を取得し、それを使用して、ID を使用してコレクションからモデルを取得しますcollection.get(id)。一部の要素にoptionは、モデル ID として意味のある自然な属性がありますが、他の要素には、単にdata-id="42"属性を使用できます。

上記よりも単純でクリーンではないと思いますが、実行可能な別のアプローチは、jQueryの.dataメソッドまたは同等のものを使用して、モデルインスタンスを要素に関連付けることです。

于 2013-07-23T02:01:21.787 に答える
2

カスタム ID などを追加する必要はありません。また、danmactough の回答は機能しないため、無視するのが最善です。MarionetteでもchildEvents、select/option タグでは機能しません。

change私の方法は、上のイベントにバインドしCollectionView、コレクション内のモデルのインデックスと:selectedドロップダウン内の要素を一致させることです:

var listView = Marionette.CollectionView.extend({
    itemView: singleView,
    tagName: 'select',
    id: 'my-selector',
    events: {
        'change': 'optionSelected'
    },
    optionSelected: function() {
      // The selected model:
      var model = this.collection.at($(':selected', this.$el).index()));
    }
});
于 2015-11-22T22:57:32.247 に答える
0

マリオネット固有のより良い解決策は、 CollectionView または CompositeView で利用可能なmodelEventsまたはcollectionEvents構成ハッシュを使用することだと思います。

var listView = Marionette.CollectionView.extend({
    itemView: singleView,
    tagName: 'select',
    id: 'my-selector',
    modelEvents: {
        'change': 'modelChanged'
    },
    modelChanged: function(e) {
      // "e" is the event
      // "this" is the ItemView
      // "this.model" is the model  
    }
});
于 2014-01-29T23:52:14.373 に答える