Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen to a specific attribute changes in a model in a nested collection in Backbone

I have the following backbone structure:

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

and I want to listen for any changes in the quantity attribute, I got it working by

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

});

But does marionette or backbone have a better way of doing it, instead of looping throught the parent collection and adding the listener to each child collection, maybe something like

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

(which didnt work for me)

like image 990
Yehia A.Salam Avatar asked Apr 27 '13 10:04

Yehia A.Salam


1 Answers

Take a look at Backbone.DeepModel. Apparently, you can represent Order as a single model with deep structure and listen to either change:order_items.*.menu_items.* or change:order_items.menu_items.*. Note that this solution prevents you from using benefits of nested lists as Backbone.Collection. I think it's a good tradeoff, but your mileage may vary

like image 61
Alexander Lebedev Avatar answered Nov 23 '22 08:11

Alexander Lebedev