Giving initial value to observable from the HTML markup

10,615

Solution 1

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:

ko.bindingHandlers.valueWithInit = {
    init: function(element, valueAccessor, allBindingsAccessor, data) {
        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] });
    }
};

You would use it like:

<input value="someValue" data-bind="valueWithInit: 'firstName'" />

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

Solution 2

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:

<input data-bind="valueWithInit: firstName" value="Joe" />

Extending on the idea, you can also use this to separate the initialization and the binding:

<input data-bind="initValue: lastName, value: lastName" value="Smith" />

This is a little redundant, but becomes useful when you're using a plugin instead of the built-in bindings:

<input data-bind="initValue: lastName, myPlugin: lastName" value="Smith" />

Expanding a little more, I also needed a way to initialize checkboxes:

<input type="checkbox" data-bind="checkedWithInit: isEmployed" checked />

And here are the handlers:

ko.bindingHandlers.initValue = {
    init: function(element, valueAccessor) {
        var value = valueAccessor();
        if (!ko.isWriteableObservable(value)) {
            throw new Error('Knockout "initValue" binding expects an observable.');
        }
        value(element.value);
    }
};

ko.bindingHandlers.initChecked = {
    init: function(element, valueAccessor) {
        var value = valueAccessor();
        if (!ko.isWriteableObservable(value)) {
            throw new Error('Knockout "initChecked" binding expects an observable.');
        }
        value(element.checked);
    }
};

ko.bindingHandlers.valueWithInit = {
    init: function(element, valueAccessor, allBindings, data, context) {
        ko.applyBindingsToNode(element, { initValue: valueAccessor() }, context);
        ko.applyBindingsToNode(element, { value: valueAccessor() }, context);
    }
};

ko.bindingHandlers.checkedWithInit = {
    init: function(element, valueAccessor, allBindings, data, context) {
        ko.applyBindingsToNode(element, { initChecked: valueAccessor() }, context);
        ko.applyBindingsToNode(element, { checked: valueAccessor() }, context);
    }
};

Notice valueWithInit simply uses initValue under the hood.

See it in action on jsfiddle.

Solution 3

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:

<form name="person">
  <input type="text" name="firstName" value="Joe" data-bind="value: firstName"/>
</form>

Then Knockout could be initialized as follows:

ko.applyBindings({
  firstName: ko.observable(document.forms['person']['firstName'].value)
});

Solution 4

You can simply use a custom binding and assign the values to the existing observables:

ko.bindingHandlers.yourBindingName = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        viewModel.dataSource($(".dataSource").val());
        viewModel.pageSize($(".pageSize").val());
    }
};

Then, just add a class, or an Id to the inputs and data-bind="yourBindingName" to the HTML element containing them.

Share:
10,615
Kassem
Author by

Kassem

Updated on June 19, 2022

Comments

  • Kassem
    Kassem almost 2 years

    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?