I have a simple jsfiddle where I’m trying to better understand value binding. I have an input control value bound to a search property on my viewModel as follows:
<input data-bind="value: search" />
I have the search property as defined as:
this.search = ko.observable("");
I also have subscribe implemented on the “search” property as follows:
this.search.subscribe(function(newValue) {
alert("New value is " + newValue);
alert("New value is" + this.search);
});
I can see newValue change as I type and then select another control, but the viewModel property search does is always undefined. I was expecting with 2-way binding that as I type information search would have the type value so that I could use it say in a button that executes a webservice call using ajax, but undefined is the only value that I can get in the field without setting the default value of the search.
Is it expected that I change the value of search in the subscribe call? I thought this would be done for me by having it 2-way bound.
Firstly, within the
subscribemethod,thisdoes not reference the view model and so there is nosearchproperty available (henceundefined). You can work around this by saving a reference to the view model under another variable name such as_selfand accesssearchusing that reference.Secondly, you need to call
searchas a function in order to get it’s value – this is true of all observable values when working with Knockout.Updated Fiddle