gpt4 book ai didi

javascript - 使用 Knockout JS 部分映射到现有对象

转载 作者:行者123 更新时间:2023-11-29 10:21:32 24 4
gpt4 key购买 nike

我有一个复杂的模型,其中包含大量 ko.observable、ko.observableArray 和包含更多此类可观察对象的嵌套对象。

现在,最初我必须在每个模型中创建方法,这些模型组合起来构成更大的模型,以获取 Json 数据,然后填充其可观察对象。现在我尝试了 ko.mapping 插件,但是当我使用它时:

ko.mapping.fromJS(jsonData, {}, existingModel);

这似乎适用于大多数对象,但是我注意到当我这样做时它似乎完全覆盖了对象,并且因为我正在使用 knockout js 验证即:

this.Name = ko.observable().extend({ required: true });
this.Age = ko.observable().extend({ required: true, digits: true });

问题是这些验证属性在使用映射模块时似乎被删除了,所以有没有办法让映射插件只更新值,而不是篡改对象模式...

如果有更好的方法将 Json 数据应用于模型,我很乐意使用 ko.mapping 以外的其他机制。

最佳答案

来自 http://knockoutjs.com/documentation/plugins-mapping.html (高级用法部分)

Sometimes it may be necessary to have more control over how the mapping is performed. This is accomplished using mapping options. They can be specified during the ko.mapping.fromJS call. In subsequent calls you don’t need to specify them again.

因此,例如,您可以尝试这样的操作:

var self = this;
var mapping = {
update: function(arg) {
var data = arg.data;

return {
Name: data.Name && self.Name(data.Name),
Age: data.Age && self.Age(data.Age)
}
}
};
ko.mapping.fromJS(data, mapping);

关于javascript - 使用 Knockout JS 部分映射到现有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10879742/

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