Right now, I can simply initialize a bunch of observables with defaults like…
self.a = ko.observable(data.A || "");
self.b = ko.observable(data.B || "");
self.c = ko.observable(data.C || "");
But if I wanted to do something like
var ViewModel = ko.mapping.fromJS(data)
And set the defaults, how do I do it?
Do I have to actually do something like
var ViewModel = function(data) {
ko.mapping.fromJS(data, {
c: {
create: function(options) { return ko.observable(options.data.c || "") }
};
}, this)
};
Which as you can see is a ton overhead. I also wanted to add, that the one benefit that stood out at me with the mapping library is that this made it possible to have one less place to update when property names change. But if indeed you have to explicitly state the property name in order to specify the create callback, that benefit is defeated.
Am I wrong and there is an easy way to cover this?
If you need to set all fields with same default values you can construct mapping options dynamically iterating all
data‘s properties:Here is working fiddle: http://jsfiddle.net/vyshniakov/tDAGU/