简体   繁体   English

如何在Ractive中显示多个属性的总和

[英]How do I display the sum of multiple properties in Ractive

I am using RactiveJS for my templates. 我正在使用RactiveJS作为模板。 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 . 这是一个小提琴 ,它通过使用Ractive的计算属性来实现您想要的。 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/ ): (请参阅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}} 然后在模板中,我可以只使用{{sum}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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