18

次のバックボーン構造があります。

- collection[order_items]
   - collection[menu_items]
        - price
        - quantity

数量属性の変更をリッスンしたいので、それを機能させました

var CheckoutView = Backbone.Marionette.ItemView.extend({

    template: '#template-checkout',

    initialize: function (options) {
        this.order_collection = options.collection;
        _(this.order_collection.models).each(function (element, index, list) {
            this.listenTo(element.get("menu_items"), "change:quantity", this.onOrderItemsChanged);
        }, this);

    },

    onOrderItemsChanged: function (model, val, options) {
        console.log(model.get("name"));
    }

});

しかし、マリオネットまたはバックボーンには、親コレクションをループして各子コレクションにリスナーを追加する代わりに、それを行うためのより良い方法がありますか?

this.listenTo(this.order_collection, "change:menu_items:quantity", this.on OrderItemsChanged)

(私にはうまくいきませんでした)

4

2 に答える 2

-8

バックボーン コレクションには、バックボーン モデルと同様に独自のイベントがあります。コレクション内のイベントをバインドするだけで、その中のすべてのモデルがリッスンします。例えば:

this.order_collection.models.on('change:quantity', function(model, updatedQuantity) {
    alert("Changed quantity from " + model.previous("quantity") + " to " + updatedQuantity););
});

したがって、コレクション内のモデルでトリガーされたイベントは、コレクションでもトリガーされます。

于 2013-04-28T13:56:01.140 に答える