Binding to a value computed from a Collection

edited March 2014 in Enyo 2.4
Hi,

I have a collection of a models, and am trying to create a binding that will bind to the sum of values of each element in the collection.

I can bind to an attribute of the collection - such as ".length" quite easily. However, when I attempt to run a transform that iterates through each item in the collection to get the total it doesn't seem to work.

More specifically, it works the first time, but the binding no longer seems to work after this.

This is my binding:
{
        from: ".itemList",        
        to: ".$.total.content",
        transform: function (val) {
            
            var total = 0;
            if (val) {
                var n = val.records.length;
                console.log("Updating Total");
                while (n--) {
                    total += val.records[n].attributes.price;
                }
            }
            total = "Total : $" + total;

            
            return total;
        }
    }
A working example is available here:

http://jsfiddle.net/harperp/u59Qk/14/

When it first loads, the "item total" correctly updates to "$30" - the sum of the two initial items's prices.

However, as I add new items, while the datalist and the count increase, the total no longer does.

Does anyone know what's going on here? I suspect it's something to do with my usage in the binding of "from: '.itemList'", but I'm not sure what the recommended way of doing this would be?

Thanks,

Pete.

Comments

  • Could you instead try binding to a property of itemList that changes as items are added, say itemList.records or itemList.length?
  • I've tried binding to itemList.records as well, but this still didn't get fired as items get added.

    Binding to itemList.length does indeed work, but I guess in this case, I don't get a reference to the entire list passed in, so I cannot work out the total entirely from the input.

    My workaround for now is to bind to the .length, and to ignore the value passed in, and just use my local reference to the collection:

    {
    from: ".itemList.length",
    to: ".$.total.content",
    transform: function (val) {
    var total = 0;
    var n = this.itemList.records.length;
    while (n--) {
    total += this.itemList.records[n].attributes.price;
    }
    total = "Total : $" + total;
    return total;
    }
    }
  • I had to solve a similar problem recently. I created a custom collection that monitored changes to the collection and published a "total" property i could bind to.

    Something like this: http://jsfiddle.net/ryanjduffy/GLvJB/
  • Thanks a million - that makes more a lot more sense than what I was trying to do.. I'll give that a go now..
Sign In or Register to comment.