2

バックボーン (実際にはマリオネット) でビューを初期化した後、そのコレクションを変更することは可能ですか? 追加のサブアイテムを含む (メイン) アイテムのリストのネストされたモデルを使用します。ビューにはすべてのメイン アイテムが表示され、それらのアイテムの現在の選択に応じて、サブ アイテム ビューが変化します。私が見る唯一のオプションは、選択が変更されたら、選択したメインアイテムのサブアイテムでサブアイテムビューを再作成することです。

モデルは次のとおりです。

model = [
  {
    foo: 'blah',
    bar: [{a: 1, b: 2, c: '3'}, {a: 4, b: 5, c: null}]
  },
  {
    foo: 'abcd',
    bar: [{a: 6, b: 7, c: '8'}, {a: 9, b: 10, c: '11'}]
  }
]

ビューには、2 つのテーブルが並んでいます。

Table1      Table2
------      ------
 blah        a=6, b=7, c='8'
*abcd        a=9, b=10, c='11'

* は、現在選択されているメイン アイテムを示します。選択時に table1 で選択したメイン アイテムのインデックスを取得できますが、table2 のビューを再初期化するにはどうすればよいですか?

編集:さらに説明するためのコードを次に示します。

var MainCollectionViewRow = Backbone.Marionette.ItemView.extend({
    template: _.template(...),
    tagName: 'tr'
});

var MainCollectionView = Backbone.Marionette.CompositeView.extend({
    tagName: 'table',
    template: _.template(...),
    itemView: MainCollectionViewRow,
    events: {
        'click tbody tr': 'selectItem',
    },
    appendHtml: function(collectionView, itemView, index) {
        $(itemView.el).data('index', index);
        collectionView.$('tbody').append(itemView.el);
    },
    selectItem: function(e) {
        var index = $(e.currentTarget).data('index');
        var newMainItem = this.collection.at(index);
        // This doesn't work...
        subView.initialize({'collection': newMainItem.get('bar')});
    }
});

var Bar = Backbone.Model.extend({
    defaults: {
        a: null,
        b: 0,
        c: 'text',
    }
});

var BarCollection = Backbone.Collection.extend({
    model: Bar
});

var Main = Backbone.Model.extend({ 
    defaults: {
        foo: null, 
        bar: BarCollection,
    },
    initialize: function() {
        var bar = new BarCollection(this.get('bar'));
        this.set('bar', bar);
    }
});

var MainCollection = Backbone.Collection.extend({
    model: Main,
    url: '/some/url/'
});

app.someRoute = function() {
    var region = new MainRegion();
    var layout = new MainLayout();
    region.show(layout);

    new MainCollection().fetch({
        success:function (list) {
            mainView = new MainCollectionView({
                collection: list
            });
            var subItem = list.first();
            subView = new SubCollectionView({
                collection: list.get('bar')
            });

            layout.main.show(mainView);
            layout.sub.show(subView);
        }
    });
}

app.route('some/route', 'someRoute');
4

1 に答える 1