Collections as a property of a class / aggregating collection items' values

11 views
Skip to first unread message

Kirill Grishin

unread,
Jun 25, 2012, 12:18:34 PM6/25/12
to seren...@googlegroups.com

Hi all,

 

I have a property 'items' in Invoice class, which is a collection of instances of InvoiceItem class. I want to aggregate the InvoiceItem.sum values and access it via Invoice.total property. I do it in the following way:

 

// Invoice Class

var Invoice = Serenade.Model.extend('Invoice', function() {

       this.property("items"); // a collection of InvoiceItem class instances

       this.property("total ",{

             get: function(){

                    // Didn't figure out how to use reduce function yet, so own implementation

                    var result = 0;

                    for (var i = 0; i < this.items.length; i++) {

                           result += this.items[i].sum;

                    }

                    return result;

             },

             dependsOn: ['items'] // This gives no effect though

       });

});

 

// InvoiceItem Class

var InvoiceItem = Serenade.Model.extend('InvoiceItem', function() {

       this.property("sum");

});

 

The question is: how do I make Invoice.total depend on the changes of the InvoiceItem.sum property?

 

I know how to do it with objects thanks to Jonas, but what about collections?

 

I also noticed that there is special syntax for defining collections as a property of an object, like the following:

 

var Invoice = Serenade.Model.extend('Invoice', function() {

this.hasMany('items', {

         as: function() { return InvoiceItem; },

         serialize: true

       });

});

 

Does this have anything to do with my question? What are the advantages of this syntax?

 

Thank you!

Jonas Nicklas

unread,
Jun 25, 2012, 12:45:27 PM6/25/12
to seren...@googlegroups.com
You can observe items in a collection by using a colon instead of a
dot in dependsOn. In this case `dependsOn: "items.sum"`. This is now
documented in the README. As for `hasMany`, the main advantage is that
it automatically casts to the correct type when you assign, so you can
use an object directly from JSON data, for example.

/Jonas

Kirill Grishin

unread,
Jun 25, 2012, 8:32:09 PM6/25/12
to seren...@googlegroups.com
Jonas, thank you! Great, everything works like a charm! I am sorry I probably have missed it in the README file. Will be more attentive next time!
Reply all
Reply to author
Forward
0 new messages