renathy
renathy

Reputation: 5345

knockout doesn't update values through mapping

This updates values on a UI:

PortfolioGeneral.CompanyName(item.CompanyName);

I can write those values hand by hand, but instead I wanted to use a mapping. However this doesn't work:

PortfolioGeneral = ko.mapping.fromJS(item);

The ko.applyBindings was already called before call of the following function. This call should update all model values.

function getPortfolioGeneral(portfolioId, PortfolioGeneral) {
    $.ajax({
        url: "/api/portfolio",
        contentType: "text/json",
        dataType: "json",
        type: "GET",
        data: { id: portfolioId },
        success: function (item) {            
            //PortfolioGeneral = ko.mapping.fromJS(item);    
            PortfolioGeneral.CompanyName(item.CompanyName);
        },
        error: function (data) {
        }
    });    
}

Upvotes: 1

Views: 44

Answers (1)

nemesv
nemesv

Reputation: 139748

With using the statement PortfolioGeneral = ko.mapping.fromJS(item); you are overriding the value of your PortfolioGeneral so your original observable properties will be replaced with new ones so KO cannot track them anymore.

What you need is to update your PortfolioGeneral properties from the data of your item object, you can do this with the following syntax:

ko.mapping.fromJS(
   item, // the source object what you want to map
   {}, // the mapping options if you want something mapped special
   PortfolioGeneral // the target object which you want to be updated
);

Upvotes: 2

Related Questions