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.
Extending during mapping:
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);
}
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.