I have finally found the time to start learning KnockoutJS while building a new MVC4 application. I am trying to figure out the best way to initialize an observable value from a default value that is already set in the view.
This is a contrived example, but I would like to render out a default value for an observable directly to the view as follows:
<input type="hidden"
value="@Model.SomeValue"
data-bind="value: myObservableReference"/>
I know that a default value is normally initialized via:
model.myObservableReference = ko.obervable("SomeValue");
However, I would like to find a way to extend the initialization such that:
model.myObservableReference = ko.obervable();
would read the existing value from the binding if a value exists.
As I have so far managed to keep my KnockoutJS code completely unaware of the razor world, I want to to avoid the sloppiness of:
model.myObservableReference = ko.obervable(@Model.SomeValue);
I am guessing this would be handled via either an extender or custom binder, but if someone could point me in the right direction it would be greatly appreciated.
To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.
applyBindings method activates Knockout and wires up the view-model to the view. Now that we have a view-model, we can create the bindings. In Knockout.js, you do this by adding data-bind attributes to HTML elements. For example, to bind an HTML list to an array, use the foreach binding: HTML Copy.
Determining if a property is a computed observable Knockout provides a utility function, ko. isComputed to help with this situation.
You could try creating your own custom binding handler to achieve this:
ko.bindingHandlers.initializeValue = {
init: function(element, valueAccessor) {
valueAccessor()(element.getAttribute('value'));
},
update: function(element, valueAccessor) {
var value = valueAccessor();
element.setAttribute('value', ko.utils.unwrapObservable(value))
}
};
<input type="hidden" value="@Model.SomeValue"
data-bind="initializeValue:myObservableReference, value: myObservableReference"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With