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!