I am working through the mapping plugin example on the Knockoutjs website.
This is the example data.
Knockout JS Mapping Plugin
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);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…