Reputation: 1986
lets assume a viewmode fromJS
var js = {
Foo1 : {
BarA : 'text',
BarB : 'other text' },
Foo2 : {
BarC : 'some text' }};
var vm = ko.mapping.fromJS(js);
ko.applyBindings(vm);
Now I can do
vm.Foo1.BarB('hello world');
I can also do somthing like
var js = {
Foo1 : {
BarA : 'text',
BarB : 'hello world' },
Foo2 : {
BarC : 'some text' }};
ko.mapping.fromJS(js, vm);
Both scenarios update any field bound to vm.Foo1.BarB
What I would like to do is something like
var foo = {
BarA : 'text',
BarB : 'hello world' };
ko.mapping.fromJS(foo, vm.Foo1);
This does not work, I also tried
vm.Foo1(ko.mapping.fromJS(foo));
//and
vm.Foo1 = ko.mapping.fromJS(foo);
None of them are working.
I need this because in my real scenario my model is return from a webservice, the updates Foo1 and Foo2 are also returned and I don't want too much custom mapping.
Upvotes: 0
Views: 44
Reputation: 5357
You don't want to do custom mappings, but considering a rest api might need to change, consider the implications of what that means if you rely on the API results directly as they are.
I.e. say you have an api result of:
{
name: 'Ryan',
title: 'Developer'
gender: 'M',
birthDate: '01-01-1984',
employeeCode: '0123156'
}
So you use that all over your markup with a bunch of stuff like:
<label data-bind="text: user.employeeCode"></label>
You have the field names litered all over your markup in 100's of places. You rely on them in computed observables, functions, and on and on and on. You have a 100% hard dependency on that API.
If that api were to change, or be replaced, and have a different format for returned data you'd have your entire application break and you'd have to fix so much stuff.
On the other hand, if you have a service layer js file that creates instances of custom objects for the api results then all you have to change is your service layer.
You can switch api's easily and not have to go change any of your observables, ui bindings, and so on. You've created a coupling layer between the app and it's back end data and you can swap couplings to change the whole backend.
I know it's not an answer to your question, but I would rethink you're api result mapping strategy or take it into consideration.
Upvotes: 0
Reputation: 547
As far as I know, it is not possible. But you can do this:
var js = {
Foo1 : {
BarA : 'text',
BarB : 'other text' },
Foo2 : {
BarC : 'some text' }};
var vm = ko.mapping.fromJS(js);
ko.applyBindings(vm);
//later, after fetching data from the webservice:
//data = {
// Foo1 : {
// BarA : 'text',
// BarB : 'other text' },
//}; note: Foo2 is not defined
ko.mapping.fromJS(data, {}, vm);
After mapping, only Foo1 (and its children) will be updated.
Upvotes: 0
Reputation: 1986
Apparently there is some mystery additional parameter..
ko.mapping.fromJS(foo, {}, vm.Foo1);
I have no idea what the second parameter does, but if you use it it works just fine.
https://stackoverflow.com/a/29598785/2968001
Upvotes: 0