简体   繁体   中英

Is it possible to create computed arrays with Knockout.js

I have a knockout.js ViewModel with an observable array:

function ItemsViewModel() {
    this.data = ko.observableArray([
        new Item(1, "One description"),
        new Item(2, "Two description"),
        new Item(3, "Three description"),
        // ... etc
    ]);
}

The Item looks like this:

function Item(id, name) {
    this.id = ko.observable(id);
    this.name = ko.observable(name);
};

Based on the observable array I have created in my ViewModel I would like to create a second computed array which would look like this:

function ItemsViewModel() {
    this.data = ko.observableArray([
        new Item(1, "One description"),
        new Item(2, "Two description"),
        new Item(3, "Three description"),
        // ... etc
    ]);

    this.computedData = // here I want to create a computed array based on the values
                        // of this.data
}

I cannot seem to find an example for how to create this computed array anywhere in the knockout.js documentation. Could you please give me an example of how to turn the first array into a computed array of the form:

this.computedData = [
    { dataItem: data[0].name + ' ' + data[0].id },
    { dataItem: data[1].name + ' ' + data[1].id },
    // ... etc.
]

You can use computed observable for this:

self.computedData = ko.computed(function() {
    return ko.utils.arrayMap(self.data(), function(item) {
        return { dataItem: item.name() + ' ' + item.id() };
    });
});

Here is working example: http://jsfiddle.net/vyshniakov/3fesA/1/

Read more about computed in documentation: http://knockoutjs.com/documentation/computedObservables.html

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