I am working through the mapping plugin example on the Knockoutjs website.
This is the example data.
var data = {
name: 'Scott',
children: [
{ id : 1, name : 'Alice' }
]
}
The example shows how to override the mapping for one of the children but how do I alter the mapping for the base object.
If for example I wanted to add a "FavouriteChild" property to Scott how would I go about it?
I assume I need to use the create function on the base mapping but I cannot find an example of the syntax anywhere.
var myChildModel = function(data) {
ko.mapping.fromJS(data, {}, this);
this.nameLength = ko.computed(function() {
return this.name().length;
}, this);
}
var mapping = {
'children': {
create: function(options) {
return new myChildModel(options.data);
}
}
}
var viewModel = ko.mapping.fromJS(data, mapping);
EDIT : From the accepted answer below I found this to work
<span data-bind='text: AdditionalProperty'>
The knockout code
var mapping = {
create: function (options) {
//customize at the root level.
var innerModel = ko.mapping.fromJS(options.data);
innerModel.AdditionalProperty = 'Hello World';
return innerModel;
}
}
var viewModel = ko.mapping.fromJS(data, mapping);
//use this as our model bindings
ko.applyBindings(viewModel);
Here is a continuation to this answer based on RP Niemeyer's solution
This answer here is based on the solution above and from his blog--Thanks for that! I thought I should add some details because it addresses when the array is not a first level object.
Note that the person is the first level object and children is a sub property of that person. The line viewModel.person = ko.mapping.fromJS(viewModel.person, mapping) wasn't intutive to me at first.
And here is a slight variation
The person object is an observable that is added or updated after it is originally created from the server json data.
Some binding code in the html
Ultimately, you'll need to put it to some use at some point like this:
Thank for your help! I couldn't have made it this far without your blog post.
Note that to define additional computed observables on a child you will need to pass another set of mapping options
You need to use a
create
method on the mapping object itself like:Another example based on the examples provided by Jason and RP Niemeyer.
data
is what we get after an ajax query, on which we add two nested observables (viewModel.weekly.selectedWeek
andviewModel.monthly.selectedMonth
):