Wednesday, October 2, 2013

subscribing to your observable in knockout.js

Whenever you have array like data in your view-model, you'd want to display in a tabular format. Assume each object in that array has observable properties; and you bind one of these properties to a text box so that user can type in the value, and thereby achieve two-way binding.

	<tbody data-bind="foreach: students">
			<td data-bind="text: name"></td>
			<td data-bind="text: age"></td>
				<input type="text" data-bind="value: grade"/>
Now what about the text box that is created for you...dynamically?

Now imagine you want to wire some jQuery UI stuff to this text box. Most of the jQuery ui api applies to elements which are part of the DOM. The text box created in the above fashion, may usually be a part of the DOM at a later stage. The previous post describes how you can wire a jquery autocomplete to one such dynamically created text box.

All of this is fine. But now I am going to introduce another topic in knockout.js, which does not seem connected to all of this...but then it somehow will be.

The concept is called a subscribable. The knockout.js framework gives you two-way binding, or, in other words, a two-way subscription. Its because of this, your model is updated when a user types something into a knockout-bound text box, and vice versa.

But what if you are simply just interested in subscribing to changes to a observable somewhere in code such that you don't need any kind of ui-bound logic tied to it?

This is where you'd want to use the subscribe method of the observable. It usually takes the form:
function ViewModel(){ = ko.observable('');

var model = new ViewModel();{
    //some logic goes here

Now whenever we do something like'Alice'), the function inside of subscribe is executed and Alice is passed as an argument to it.

Now lets go back to our jquery autocomplete exercise. Does all this yet give you an idea as to how you can improve the functionality of autocomplete, and thereby achieve two-way binding?


No comments: