lunedì 2 marzo 2015

A really fast getting started to knockout.js

There are tons of articles about knockout.js out there, event the official website can give you a fast intro about this library. What I'm trying to do here is to show you knockout.js in a different manner, so that you can start using it by following his documentation right away.

Intro

Knockout.js is a javascript library that can amazingly speed up the developing of your javascript RIA, by creating a binding between the content of DOM (the web page) and a javascript object that holds the rappresentation of the dynamic aspects we want to change.

Model View ViewModel

It permits to easly implement the pattern MVVM, in witch a View Model object holds the representation of the view want to dynamically change, by effecting the view model only.

Knockout.js creates a binding between the View and ViewModel, this really helps the developer by dealing with updates of the view by javascript/jquery, so that he can focus more on the business logic of his application.
Knockout doesn't have anything to do with the ViewModel-Model binding, since the Model is often on remote machines, you have to implement it yourself by means of ajax.

The ViewModel object

The first thing to do is to define your ViewModel object, this object will hold ko.objservable objects, which value will be bound to the html view.

var myViewModel = {
    personName: ko.observable('Bob'),
    personAge: ko.observable(123)
};
After that all you need to do is apply the binding.

ko.applyBindings(myViewModel);

Remember to include your .js script at the bottom of the html page before closing </html>

Binding to the View

Now to define the binding we use the attribute data-type on the specific html tags we want to dynamically change. The data-bind attribute has it's syntax, that permits to bind the defined observable in the viewmodel to a specific "quality" of that tag (graphics, text, inner html, etc).
The name is <span data-bind="text: personName"></span>
This example is telling knockout to bind the text property of the span tag to the observable defined in myViewModel called personName. So now, every time we want to change the text into that span in our .js script we can easly do it by writing:

myViewModel.personName('Bob');

Naturally you can affect any other property already defined by knockout.js, all you have to do is using another binding attribute instead of the text one. You can also bind to specific html or css attributes, just check the documentation.
an>