A couple of options for you besides just manually managing your view model. The mapping plugin supports a create
callback that lets you customize how it gets created. This can be used to add default properties to an object, if they happen to be missing.
Something like this: http://jsfiddle.net/rniemeyer/WQGVC/
Another alternative is to use a binding that creates properties that are missing. It might look like:
//create an observable if it does not exist and populate it with the input's value
ko.bindingHandlers.valueWithInit = {
init: function(element, valueAccessor, allBindingsAccessor, data) {
var property = valueAccessor(),
value = element.value;
//create the observable, if it doesn't exist
if (!ko.isWriteableObservable(data[property])) {
data[property] = ko.observable();
}
//populate the observable with the element's value (could be optional)
data[property](value);
ko.applyBindingsToNode(element, { value: data[property] });
}
}
You would use it like this (need to pass the property as a string, otherwise it will error):
<input data-bind="valueWithInit: 'name'" />
Sample here: http://jsfiddle.net/rniemeyer/JPYLp/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…