DCSIMG
KnockoutJS–The Observables - Ran Wahle's blog

Ran Wahle's blog

KnockoutJS–The Observables

KnockoutJS–The Observables

On my previous post, I’ve demonstrated a simple exampleKnockoutJS of data binding between our HTML content (view) and our Javascript (view-model). On this post I’ll dive, not deeply, to the javascript  on our view-model and explain some of it’s basics, the ones that causes it to act as a real view-model.

ko

KO stands for Knockout and it will be used whenever we use the KnockoutJs library

ko.observable()

This function, of the KnockoutJs library notifies the view of every change of the bounded member’s value. Please note that in Javascript you don’t have actual properties (unlike C#) and you cannot use simple assignment syntax to invoke get method. Therefore, whenever you change member you use <member name>(<new value>).  The library upon invocation will reflect the change on the browser’s screen.

Binding in KnockoutJs is two-way. (There is no binding-mode like XAML), meaning that the user changes the values whenever the member is bounded to an editable element (textbox, checkbox, combo-box etc.).

The observable method can be invoked with no parameters or with a value of which the member is initialized with.

For collections we have the observableArray who can have an empty array as parameter ([])  or with some items (syntax: ko.observableArray('[{item1, item2, …]}) );

More about collections when I talk about templates.

ko.applyBindings

That’s the command that set’s the HTML page’s data-context (XAML term once again). It get’s our view-model as a parameter.

Summary:

In this post I’ve reviewed some of the basic code of the view-model javascript.  For every member we wish to bind we have to declare it as ko.observable or as ko.observableCollection for collections. At the end we should invoke the ko.applyBindings function which actually binds the data to the HTML element, or set the HTML page’s data context if you prefer XAML terminology.

Note: The ko.applyDataBindings() should come after the HTML content, otherwise it won’t know where to bind the data to.

kick it on DotNetKicks.com

Comments

KnockoutJS???Templates - Ran Wahle's blog said:

Pingback from  KnockoutJS???Templates - Ran Wahle&#39;s blog

# December 1, 2011 4:30 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: