I am translating my model from the server using ko.mapping.fromJS(data, mapping) method, so that i can add more properties to my sub models.
following the example here: http://knockoutjs.com/documentation/plugins-mapping.html => "Customizing object construction using “create”
here is my code:
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);
so far this works ok!
the problem happens here:
model.addEmployer = function (options, o2) {
var e = new Employer(options);
this.Resume.Employers.push(e);
};
i am missing something here.. when i want to add a new object to the collection, it is missing all the properties that came from the model (from the server) which were added on with this line "ko.mapping.fromJS(data,{}, this); " inside the Employer constructor.
i am guessing i need to repeat some similar mapping inside the addEmployer function that will re-bind all server side properties to the client model
here is how i'm calling addEmployer:
<button data-bind="click: addEmployer">...</button>
UPDATE
what it boils down to, is when declaring 'create' event in the mapping, that function receives options object, which has options.data which can be used in this call: ko.mapping.fromJS(data,{}, this); .. i am not sure how to get this type of object in my addEmployer handler, to provide necessary bindings for all the properties that exist on Employer object on the servier.
i can sort of hack it by preserving that options.data from initial binding, and re-using that in the addEmployer handler. the problem with that, is it will have all the properties set from that initial object.
what i basically need, is EmployerMappingOptions object that is empty. in the above implementation, options.data comes pre-populated with data on the first Employer object in my collection. how can i get that mapping data for empty Employer model?