Boas Enkler
Boas Enkler

Reputation: 12557

Knockout.js computed array property

I've a KnockoutViewModel ViewData this has an array of Items. These items are read from a server with $post.

Now this items have each an id and a link field. the id can be changed in the ui via a combobox. When the id changed, i want to update the link.

For this i re-assigned the id property to be observable and create the link property as computed.

As a result the computed event is raised. But i don't know how to reference the link field correctly. using the item reference, i always get the latest element which was processed in the the for loop.

    $.post(url,
        function (data, status) {

            for (var index = 0; index < data.length; ++index) {
                item.Id = ko.observable(data[index].Id);
                item.Link = ko.computed(function () {
                    return  url.replace(urlTemplate, item.Id());;
                });
            }
            self.items(data);
        });
}

I also tried to create a ItemModel to represent the item and convert each server element to a new ItemModel,but then i see for each entry the data of the last item.

what am i doing wrong ?

  $.post(url,
                function (data, status) {
                    var items = $.map(data, function (item) { return new ItemModel(item) });
                    self.items(items);
                });

Upvotes: 0

Views: 53

Answers (1)

aup
aup

Reputation: 810

Try creating a new item object for each in the in the for loop. Something like this,

self.items = ko.observableArray();
for (var index = 0; index < data.length; ++index) {
       var item = {
           Id: ko.observable(data[index].Id),
           Link: ko.computed(function () {
                 return url.replace(urlTemplate, data[index].Id);
           });
       };
self.items.push(item);
}

Upvotes: 1

Related Questions