Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout is not mapping the properties of an object in an array

It seems that knockout is not mapping the properties of objects in an array correctly.

See this example from the chrome console:

> var viewmodel = ko.mapping.fromJS({list:[]});
undefined

> viewmodel.list().unshift({ name : ko.observable("Foo") });
1

> viewmodel.list()[0].name();
"Foo"

> var js = ko.mapping.toJS(viewmodel);
undefined

> js.list[0].name;
undefined

So the javascript object is being created, but the 'name' property does not get mapped.

Any ideas are very welcome!

like image 881
Richard Astbury Avatar asked Apr 16 '12 13:04

Richard Astbury


1 Answers

From http://knockoutjs.com/documentation/plugins-mapping.html, about the toJS() function:

This will create an unmapped object containing only the properties of the mapped object that were part of your original JS object.

As "name" was not part of the original object you mapped, it does not get unmapped. You need to tell the mapping plugin to include this specific property:

var js = ko.mapping.toJS(viewmodel, { include: ['name'] });
like image 121
Niko Avatar answered Oct 16 '22 10:10

Niko