I’m attempting to gradually sprinkle KnockoutJS into my existing application. My first stab at this is to take some small existing forms and have their values pushed to the server on blur as well as updating some elements via binding.
The issue I’m running into is that when the form is first displayed it is not being populated via knockout. I’m rendering the page with the data already in the form. So I setup my knockout like this:
function DomainViewModel() {
this.name = "";
this.description = "";
}
ko.applyBindings(new DomainViewModel());
And I have my form like so:
<input data-bind="value: name" value="${domainInstance.name.encodeAsHTML()}"/>
<textarea data-bind="value: description" >${domainInstance.description.encodeAsHTML()}</textarea>
So what is happening is my form is displayed and then knockout applies the values from the ViewModel to the form, which wipes out the values that were put there by the server. I understand why this happens and that this is not a bug. However, I’m wondering if there is another option here.
I know that I could do something like the following:
function DomainViewModel() {
this.name = "${domainInstance.name}";
this.description = "${domainInstance.name}";
}
But that would require me to put some of the javascript directly in the GSP (I’m using Grails) rather than an external script file.
So, you have a few ways you could do this. First, never do this
Your viewmodel has just become un-reusable. If you want to use grails to populate the viewmodel, set some javascript object on the page, and pass that into your external javascript file viewmodel definition, like this (don’t forget to make your properties obsevables!):
I would recommend this approach, because later when you change the source of the data, you don’t have to alter the HTML. However, there is another option. You could create a binding that collected the value from the elements and use it to set the initial observable values. That binding might look like this:
Here is a fiddle demonstrating this method in action