gmac / backbone.epoxy

Declarative data binding and computed models for Backbone
http://epoxyjs.org
MIT License
615 stars 89 forks source link

How to create a computed based on a collection? #100

Closed jefersondaniel closed 10 years ago

jefersondaniel commented 10 years ago

I have a code following that example and want to listen to collection changes and recompute the charged amount:

Backbone.Epoxy.Model.extend({
    defaults: {
        id: null,
        items: new Backbone.Collection(),
        discount: 0,
    },

    computeds: {
        chargedAmount: {
            deps: ['discount', 'items'],
            get: function(discount, items) {
                //calculate total amount
            },
        },
    }
}

But it does not work. What are the alternatives?

gmac commented 10 years ago

This would be a situation to roll your own implementation. Collection bindings are really hard to automate efficiently, simply because a collection has so many events, each of which can potentially trigger at a high magnitude (ie: across N models). Epoxy is deliberately conservative about binding to collections for this reason. You're a lot better judge of what triggers your application needs, and how best to hook into them as efficiently as possible.

jekuno commented 8 years ago

For anybody who might stumble upon this lateron: see #25 regarding recomputing of computeds based on collections.

Also see http://epoxyjs.org/documentation.html#handler-collection Note that the collection binding does not register a "change" event on its collection to avoid generally superfluous updates. Instead, you may manually trigger an "update" event on the collection to refresh its bindings. For a working demonstration of the collection binding, see the Epoxy ToDos demo.