knockout.js partial mapping from json

2019-09-09 19:50发布

问题:

On the knockout.js site's documentation they say that when you get data back from the server you can do this:

// Every time data is received from the server:
ko.mapping.fromJS(data, viewModel);

I'd like to partially map the data back into my object model. Is that possible?

I have a viewModel.jobs[i].JobType child object, so I'd like to do something like this:

ko.mapping.fromJS(data.jobType, viewModel.jobs[i].JobType);

... meaning I'd like to just map in the jobType from the result from the server into this specific job's JobType field.

... Also keeping in mind:

// does not work because viewModel.jobs[i].JobType() is not a function.
viewModel.jobs[i].JobType(data.JobType);

回答1:

This worked:

ko.mapping.fromJS(data.job, viewModel.jobs[i]);