Javascript 敲除的动态可观察类
我正在从事一个与报告相关的项目,在这个项目中,我需要构建大量使用KO呈现的报告。使用AJAX提取所有数据并更新模型。目前,我正在编写大量的js函数来映射模型。比如:Javascript 敲除的动态可观察类,javascript,ajax,knockout.js,Javascript,Ajax,Knockout.js,我正在从事一个与报告相关的项目,在这个项目中,我需要构建大量使用KO呈现的报告。使用AJAX提取所有数据并更新模型。目前,我正在编写大量的js函数来映射模型。比如: function modelx(child) { var self = this; self.Name = ko.observable(child.Name); self.Relation = ko.observable(child.Relation); // hundred other proper
function modelx(child) {
var self = this;
self.Name = ko.observable(child.Name);
self.Relation = ko.observable(child.Relation);
// hundred other properties
};
function modely(child) {
var self = this;
self.Age = ko.observable(child.Age);
self.Relation = ko.observable(child.Relation);
// hundred other properties
};
var modelxInstance= ko.mapping.fromJS(child);
在AJAX调用之后,我将填充可观察数组
for (var i = 0; i < jsn.length; i++)
{
VM.modelxlist().push(new modelx(jsn[i]));
}
for (var i = 0; i < jsn1.length; i++)
{
VM.modelylist().push(new modely(jsn1[i]));
}
有没有办法避免modelx、modely等的定义,。。。这样,当在HTML中使用时,模型会自动构建,而不会失去这种方法的好处?当然,可能有一种情况,我可能无法从服务器获取特定的属性,我应该在服务器端进行检查
此外,有时我可能需要添加额外的计算观测值,以便更加灵活为什么不使用敲除映射插件: 然后,您将得到如下结果:
function modelx(child) {
var self = this;
self.Name = ko.observable(child.Name);
self.Relation = ko.observable(child.Relation);
// hundred other properties
};
function modely(child) {
var self = this;
self.Age = ko.observable(child.Age);
self.Relation = ko.observable(child.Relation);
// hundred other properties
};
var modelxInstance= ko.mapping.fromJS(child);
有几个用于knockout的映射插件,我最喜欢的实际上是这个:
原因是它更易于配置,速度更快。我想这正是您想要的
使用ko.mapping.fromJS方法,您可以自动观察对象的所有属性。。
花点时间读一读这篇文章。你总是可以制作一些可重用的函数来减少重复。这不是你想要的吗?