在淘汰赛中扩展动态数据和映射数据 [英] Extending dynamic and mapped data in Knockout
问题描述
使用Knockout.JS,我试图确定如何通过映射插件加载和动态添加对象时,如何最好地扩展视图模型中的对象.在此示例中,我向Person对象添加了addChild方法.
Using Knockout.JS, I'm trying to determine how to best extend objects in the view model when they will be both loaded via the mapping plugin and dynamically added. In this example, I'm adding a method addChild to the Person object.
在映射过程中扩展:
var myPersonModel = function (data) {
ko.mapping.fromJS(data, {}, this);
this.addChild = function () {
this.children.push(new Child());
} .bind(this);
}
var mapping = {
'people': {
create: function (options) {
return new myPersonModel(options.data);
},
}
}
var viewModel = ko.mapping.fromJS(data, mapping);
在动态创建过程中扩展:
Extending during dynamic creation:
function Person(id, name, children) {
this.id = ko.observable(id);
this.name = ko.observable(name);
this.children = ko.observable(children);
this.addChild = function () {
this.Forms.push(new Child());
} .bind(this);
}
但是在我看来,必须有一种更简单的方法来执行此操作,这样我就不必重复自己了,映射对象和新对象都可以使用addChild
方法.
But it seems to me there must be an easier way to do so such that I don't need to repeat myself, and both mapped and new objects get the addChild
method.
推荐答案
看看此答案,尤其是 JSFiddle上的实时示例.
看起来您的代码已接近所需的代码.
It looks like your code is close to what it needs to be.
我认为您只需要将mapping
和ko.mapping.fromJS
折叠到您的Person
构造函数中即可.
I think you just need to fold mapping
and ko.mapping.fromJS
into your Person
constructor.
这篇关于在淘汰赛中扩展动态数据和映射数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!