gpt4 book ai didi

knockout.js - ko.mapping创建函数,扩展对象

转载 作者:行者123 更新时间:2023-12-04 13:24:17 24 4
gpt4 key购买 nike

是否可以在映射过程中修改(缺少更好的术语)对象的架构?我想是的,我似乎无法使它正常工作。我正在尝试这样的事情:

var data = {
itemOne: 'someData',
itemTwo: 'moreData'
}

var mapping = {
"newItem": {
create: function(options) {
return ko.observable(false);
}
}
};

ko.mapping.fromJS(data, mapping, _model.observableArrayPart);

最佳答案

这是一个示例,该示例显示自定义数组如何创建和为其定义键,以便您可以使用映射插件来应用更新:http://jsfiddle.net/rniemeyer/LHeQZ/

var data = [
{ id: 1, first: "Bob", last: "Smith" },
{ id: 2, first: "Jim", last: "Jones" },
{ id: 3, first: "Delete", last: "Me" }
];

var updatedData = [
{ id: 1, first: "Robert", last: "Smith" },
{ id: 2, first: "James", last: "Jones" },
{ id: 4, first: "New", last: "Guy" }
];

var Person = function(data) {
this.id = data.id;
this.first = ko.observable(data.first);
this.last = ko.observable(data.last);
this.full = ko.computed(function() {
return this.first() + " " + this.last();
}, this);
};


var dataMappingOptions = {
key: function(data) {
return data.id;
},
create: function(options) {
return new Person(options.data);
}
};


var viewModel = {
people: ko.mapping.fromJS([]),
loadInitialData: function() {
ko.mapping.fromJS(data, dataMappingOptions, viewModel.people);
},
loadUpdatedData: function() {
ko.mapping.fromJS(updatedData, dataMappingOptions, viewModel.people);
}
};

ko.applyBindings(viewModel);

关于knockout.js - ko.mapping创建函数,扩展对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9779969/

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