我正在使用 ko.mapping.fromJS(data, mapping) 方法从服务器转换我的模型,以便我可以向我的子模型添加更多属性。
按照此处的示例:http: //knockoutjs.com/documentation/plugins-mapping.html =>“使用“创建”自定义对象构造</p>
这是我的代码:
var Employer = function (data) {
ko.mapping.fromJS(data,{}, this);
this.Foo = ko.observable("bar"); // added properties will go here.
console.log(this.Foo()); // i see this getting called OK on initial creation, and subsequent creations
console.log(this.Name()); // ** this is only OK during initial creation, but on subsequent times i get "[Object] does not have a property Name" this property comes from the server model..**
};
var mapping = {
'Employers' : {
create: function (options) {
var e = new Employer(options.data);
return e;
}
}
};
model = ko.mapping.fromJS(data, mapping);
到目前为止,这工作正常!
问题发生在这里:
model.addEmployer = function (options, o2) {
var e = new Employer(options);
this.Resume.Employers.push(e);
};
我在这里遗漏了一些东西..当我想向集合中添加一个新对象时,它缺少来自模型(来自服务器)的所有属性,这些属性是通过这一行添加的“ko.mapping.fromJS(数据,{}, this); " 在 Employer 构造函数中。
我猜我需要在 addEmployer 函数中重复一些类似的映射,它将所有服务器端属性重新绑定到客户端模型
这是我如何调用addEmployer:
<button data-bind="click: addEmployer">...</button>
更新
归结为,当在映射中声明“创建”事件时,该函数接收选项对象,该对象具有可在此调用中使用的options.data:ko.mapping.fromJS (data,{}, this); .. 我不确定如何在我的 addEmployer 处理程序中获取这种类型的对象,以便为服务器上的 Employer 对象上存在的所有属性提供必要的绑定。
我可以通过保留初始绑定中的 options.data 并在 addEmployer 处理程序中重新使用它来破解它。问题在于,它将具有从该初始对象设置的所有属性。
我基本上需要的是 EmployerMappingOptions 对象,它是空的。在上述实现中,options.data 预先填充了我集合中第一个 Employer 对象的数据。我怎样才能获得空雇主模型的映射数据?