是否有可能在映射过程中修改对象(缺少更好的术语)模式?我想是的,我似乎无法让它发挥作用.我正在尝试这样的事情:
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",first: "James",{ 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,viewmodel.people); } }; ko.applyBindings(viewmodel);