简体   繁体   中英

How do I display the sum of multiple properties in Ractive

I am using RactiveJS for my templates. I have some nested data like this:

var view = new Ractive({
    data: {
        items: [
            { size: 1 }
            { size: 3 }
            { size: 4 }
        ]
    }
});

How can I display the sum of item sizes in my template? This depends on the size of each individual item but also on the items array (eg items are added/removed).

Here is a fiddle which achieves what you want by using Ractive's computed properties . Would you consider this denormalization of data?

    computed: {
       sum: function () { 
           var items = this.get( 'items' ); 
           return items.reduce(function(prev, current) {
             return prev + current.size;
           }, 0)
       }

You can track the sum using an observer. This has the advantage of not having to reiterate the entire array each time a value changes. (see http://jsfiddle.net/tL8ofLtj/ ):

oninit: function () {
    this.observe('items.*.size', function (newValue, oldValue) {
        this.add('sum', (newValue||0) - (oldValue||0) );
    });
}

I found one solution, but it's not optimal because it denormalizes data in the view.

var view = new Ractive({
    data: {
        items: [
            { size: 1 }
            { size: 3 }
            { size: 4 }
        ],
        sum: 0
    },
    oninit: function () {
        this.observe('items items.*.size', function () {
            this.set('sum', _.reduce(this.get('items'), function (memo, item) {
                return memo + item.size;
            }, 0));
        });
    }
});

And then in the template I can just use {{sum}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM