简体   繁体   中英

Knockout get object from observableArray

I have an observableArray in my Knockout app and I'm wondering how I can go about selecting only the targeted object within the array.

I have the following code which calculates the total of all 'value's within the array but I'd like to be able to just select, say, only the second 'value' within the array.

self.csu_treatment_inputs = ko.observableArray([
                {
                    value: ko.observable(10),
                    image: ko.observable('')
                },
                {
                    value: ko.observable(120),
                    image: ko.observable('')
                },
                {
                    value: ko.observable(160),
                    image: ko.observable('')
                },

            ]);

self.totaltest = ko.computed(function () {
            var total = 0;
            ko.utils.arrayFilter(self.value_inputs(), function (item) {
                  total += parseFloat(ko.utils.unwrapObservable(item.value));
            });
            return total;
    });

To bind to the second value, use this code:

<span data-bind='text: csu_treatment_inputs()[1].value'></span>

Exemple: http://jsfiddle.net/v6T5T/

If you want to access an element from javascript, use this:

total+= parseFloat(self.test_values()[i].value());

Exemple: http://jsfiddle.net/v6T5T/2/

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