I'm trying to create an HtmlHelper
extension that outputs some HTML to the view. In this HTML I'm wiring up some KnockoutJS binding. I'm new to KO so I'm still struggling in getting some things done. Anyway, what I'm trying to do is generate input fields (in the server-side code) bound to observables on my client-side code, then set the initial values of the observables through the value of the hidden fields. Unfortunately, that is not working for me. So I'm wondering if there any way I could get this done (even if I have to do it completely different).
Here's what I'm basically doing:
In my client side view model I have the following:
self.dataSource = ko.observable();
self.pageSize = ko.observable();
And my extension method outputs the following:
<input type="hidden" value="/Employee/Get" data-bind="value: dataSource" />
<input type="hidden" value="30" data-bind="value: pageSize" />
But when the page renders, when I inspect the elements I notice that the value
of the input fields is being set to an empty string, which I believe is because of the way observables are being declared. But is there a way to override this behavior or something?
If a custom binding is too heavyweight then a simple solution is to initialize the observables from the DOM.
For example, given the following HTML form:
Then Knockout could be initialized as follows:
You can simply use a custom binding and assign the values to the existing observables:
Then, just add a class, or an Id to the inputs and
data-bind="yourBindingName"
to the HTML element containing them.One alternative you can use to keep your code a bit cleaner is to use a custom binding that wraps the value binding by initializing it with the element's current value.
You can even have it create observables on your view model, if they don't exist.
The binding might look something like:
You would use it like:
Note that the property name is in quotes, this allows the binding to create it, if it does not exist rather than error out from an undefined value.
Here is a sample: http://jsfiddle.net/rniemeyer/BnDh6
A little late here. I wasn't actually satisfied with RP's answer, because it breaks the declarative nature of Knockout. Specifically, if you use valueWithInit to define your property, you can't use it in an earlier binding. Here's a fork of his jsfiddle to demonstrate.
You use it the same way, yet it's still document-wide declarative under the hood:
Extending on the idea, you can also use this to separate the initialization and the binding:
This is a little redundant, but becomes useful when you're using a plugin instead of the built-in bindings:
Expanding a little more, I also needed a way to initialize checkboxes:
And here are the handlers:
Notice
valueWithInit
simply usesinitValue
under the hood.See it in action on jsfiddle.