问题描述
我正在研究Knockoutjs网站上的映射插件示例.
I am working through the mapping plugin example on the Knockoutjs website.
这是示例数据.
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.
例如,如果我想向Scott添加"FavouriteChild"属性,我将如何处理?
If for example I wanted to add a "FavouriteChild" property to Scott how would I go about it?
我假设我需要在基本映射上使用create函数,但在任何地方都找不到语法示例.
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'>
敲除代码
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);
推荐答案
您需要在映射对象本身上使用create
方法,例如:
You need to use a create
method on the mapping object itself like:
var mapping = {
//customize at the root level.
create: function(options) {
//first map the vm like normal
var vm = ko.mapping.fromJS(options.data);
//now manipulate the returned vm in any way that you like
vm.someProperty = "test";
vm.someComputed = ko.computed(function() {
return vm.first() + " " + vm.last();
});
//return our vm that has been mapped and tweaked
return vm;
}
};
这篇关于将属性添加到使用Knockout JS映射插件创建的视图模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!