I have a script that initializes knockout by applying an empty viewmodel to my form.
When the user enters data in the form, the viewmodel is updated accordingly – that is the expected behavior.
JavaScript
var viewModel = {
myField : ko.observable(),
init : function (somedata) {
...
ko.applyBindings(this, container);
},
...more stuff...
}
Partial
<%:Html.TextBoxFor(x => x.MyField, new Dictionary<string, object> { { "data-bind", "value: myField, valueUpdate: 'keyup'" } })%>
When i call my javascript to apply knockout in an existing form, the value already in MyField (and then in my input field) is wiped with the empty data in my knockout viewmodel (that viewmodel is part of my javascript residing in another file).
When the page is loaded, MVC makes sure that the MyField input element is filled with the previously entered data from MyField. When init is called, that field is overwritten with the value in the viewmodels myField which is empty, as it’s a static JavaScript file.
How do I solve this problem?
I have tried two approaches to handling something like this:
1- If you have good control over your server-side (which it looks like you do), then you could consider outputting javascript in your view that sets the observables to the proper values.
Would be somewhat similar to this: http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/. At least this part of it:
You could either do that and integrate the initialData before calling applyBindings or possibly just emit the javascript that directly sets your observables to the proper values.
2- If you don’t have good control over your server-side (a 3rd party control or just something that you are unable/unwilling to change at this point), then you could consider initializing your viewModel after the page has loaded, but before you call applyBindings. You would find the elements that you are interested, read meta-data or values off of them, and set your observables prior to letting the bindings do their work.
Maybe one complication for you is that sounds like currently all of your javascript is in a separate file.