gpt4 book ai didi

javascript - Knockout.js 向子元素添加属性

转载 作者:行者123 更新时间:2023-12-03 04:32:07 26 4
gpt4 key购买 nike

我的代码不会在由knockout.mapping.fromJS映射的knockout View 模型的子元素下创建新属性。

我有:

//model from Entity Framework
console.log(ko.mapping.toJSON(model));
var viewModel = ko.mapping.fromJS(model, mappingOption);
ko.applyBindings(viewModel);
console.log(ko.mapping.toJSON(viewModel));

第一个console.log输出:

{
"Id": 0,
"CurrentUser": {
"BoardIds": [
{
"Id": 0
}
],
"Id": 1,
"UserName": "foo",
"IsOnline": true
},
"Boards": []
}

然后映射选项是:

var mappingOption = {
create: function (options) {
var modelBase = ko.mapping.fromJS(options.data);

modelBase.CurrentUser.UserName = ko.observable(model.CurrentUser.UserName).extend({ rateLimit: 1000 });

//some function definitions

return modelBase;
},
'CurrentUser': {
create: function (options) {
options.data.MessageToPost = ko.observable("test");
return ko.mapping.fromJS(options.data);
}
}
};

我提到了this post创建自定义映射,但它似乎不起作用,因为第二个 console.log 向第一个 console.log 输出相同的 JSON。

此外,我尝试基于 this thread 创建嵌套映射选项和 another one但它也不起作用。

var mappingOption = {
create: function (options) {

//modelBase, modifing UserName and add the functions

var mappingOption2 = {
'CurrentUser': {
create: function (options) {
return (new(function () {
this.MessageToPost = ko.observable("test");
ko.mapping.fromJS(options.data, mappingOption2, this);
})());
}
}
}
return ko.mapping.fromJS(modelBase, mappingOption2);
}
};

如何正确地将新属性添加到原始 View 模型?

最佳答案

来自映射documentation对于 ko.toJS(toJS 和 toJSON 的工作方式与文档中所述相同)

  • Unmapping

If you want to convert your mapped object back to a regular JS object, use:var unmapped = ko.mapping.toJS(viewModel);This will create an unmapped object containing only the properties of the mapped object that were part of your original JS object

如果您希望 json 包含您手动添加的属性,请使用 ko.toJSON 而不是 ko.mapping.toJSON 来包含所有内容,或者使用 include首次创建对象时的选项来指定要添加的属性。

var mapping = {
'include': ["propertyToInclude", "alsoIncludeThis"]
}
var viewModel = ko.mapping.fromJS(data, mapping);

编辑:在您的具体情况下,您的映射选项彼此冲突。您已为 CurrentUser 字段设置了特殊指令,但随后在创建函数中覆盖了它们。我认为您的映射选项应该如下所示:

var mappingOption = { 
'CurrentUser': {
create: function (options) {
var currentUser = ko.mapping.fromJS(options.data, {
'UserName': {
create: function(options){
return ko.observable(options.data);
}
},
'include': ["MessageToPost"]
});
currentUser.MessageToPost = ko.observable("test");
return ko.observable(currentUser).extend({ rateLimit: 1000 });
}
}
};

这是一个 fiddle一个工作示例

关于javascript - Knockout.js 向子元素添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43446088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com