Value-binding without overwriting the element value property

https://groups.google.com/d/topic/knockoutjs/K-xyD1PghMk/discussion

by rniemeyer

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<p>First name: <input id="firstName" value="Reinaldo" data-bind="valueWithInit: 'firstName'"  /></p>
<p>Last name: <input id="lastName" value="Junior" data-bind="valueWithInit: 'lastName'"  /></p>

<hr />

<pre data-bind="text: ko.toJSON(viewModel, null, 2)"></pre>

CSS

input { margin: 2px; }

JavaScript

ko.bindingHandlers.valueWithInit = {
    init: function(element, valueAccessor, allBindingsAccessor, data, context) {
        var property = valueAccessor(),
            value = element.value;

        //create the observable, if it doesn't exist 
        if (!ko.isWriteableObservable(data[property])) {
            data[property] = ko.observable();
        }
        
        data[property](value);
        
        ko.applyBindingsToNode(element, { value: data[property] }, context);
    }
};

//firstName is an existing observbale
//lastName does not exist, but is created by the binding
var viewModel = {
    firstName: ko.observable("")
};

ko.applyBindings(viewModel);