[Blog Post] What’s knockout.js? And First Example!


knockoutLogo

Hi everyone,

Today, we are going to talk about knockout.js. I’m pretty sure that almost everyone who is a developer or who wants to develop something might have heard this amazing library. Truth be told, There are a lot of technologies to wait you to learn them and, of course, you should do. Also, you have to be through…

Data binding is very common feature in development today without doubt. Knockout.js(KO) presents that feature to JavaScript and HTML. KO which was developed by Steve Sanderson who is a Microsoft Employee is a open source javascript library with MIT for you to create rich display using Model-View-ViewModel(MVVM). Simply tell, KO helps you to update a sections of UI dynamically by user’s behavior on UI or whenever external data source or domain data changes.

Features and benefits but not limited:

  • automatically updates the your UI when your data model changes
  • easy to connect your UI to data model
  • extensible with a few line codes
  • works with any server or client-side technology
  • no requires to change your architecture when add KO to your web application
  • very light (13kb using GZIP)
  • support all major browsers including IE6+, Chrome, FF2+, Opera, Safari

KO will be familiar for developers work on Ruby On Rails, ASP.NET MVC or other MVC technologies.

jQuery vs knockout.js

Somebody get confused jQuery with KO. jQuery is low-level way to control/change elements and manage event handlers in web pages. KO is here for totally different problem. For example;

Imagine that there is a software development competition like ImagineCup on the web. To upload a project to the competition is necessary for each group. There are  a table  has 3 columns for the groups which are firstName, lastName, birthdate and an “Add” button which is for everymember when there are fewer than-equal 4 members on the upload page.  jQuery can not understand schema of your data model, the number of the TDs/TRs in the table or the number of DIVs with related CSS classes. In the meanwhile, when you need to implement like that item for every member is to create a lot of jQuery functions. Besides, you must disable the “Add” button after the number of TRs is 4.

Oh dear, KO does it easily. Just use a foreach binding to turn into your array(has your items) a TABLE or DIVs. The array changes, the UI changes dynamically.

Display the number of members as follows;

There are <p data-bind="text: myMembers().count"></p> items

“Add” button Enable or Disable depending on the number of member;

<button data-bind="enable: myItems().count < 5">Add</button>

As you can see, KO does not work with jQuery or similar low-level DOM APIs. KO represent you to link the data model to a UI. And yes, you don’t need jQuery to use KO.

Install/Download Knockout

Download here. And then, reference it to your page inside head tags, just write;

"<script type='text/javascript' src='knockout-2.2.1.js'></script>"

CDN(Content Delivery Network)

Microsoft Ajax CDN

More Information about Knockout:

Example

Normally, I always develop like that example on Visual Studio but for this example, I will not do! I’m going to use JSFIDDLE.net which simulates AJAX calls, HTML, CSS, JS codes is easy to use. I’m sure you will love JSFIDDLE🙂

First Screen:

What_s_knockout_js_And_First_Example!_jsfiddle_net.

Let’s add Knockout.js to our page. Just click the dropdownmenu under “Frameworks & Extenions” on left of the page.

What_s_knockout_js_And_First_Example_jsfiddle_net_knockout

Now, paste followings codes to HTML(View) side of JSFIDDLE:

<p>First name: <strong data-bind=”text: firstName”></strong></p>
<p>Last name: <strong data-bind=”text: lastName”></strong></p>
<p>Birthdate: <strong data-bind=”text: birthdate”></strong></p>

What_s_knockout_js_And_First_Example_jsfiddle_net_knockout_html

When you click the “run” button on top of page, It doesn’t work as exactly what we want because we haven’t bound and activated knockout.js yet.

Copy-Paste followings code and click the “Run” button:

function myViewModel() {
    this.firstName = “Mahmut”;
    this.lastName = “Sozeri”;
    this.birthdate = 1989;
}

What_s_knockout_js_And_First_Example_jsfiddle_net_knockout_html_paste_ViewModel

Ok, We’ve pasted javascript codes. But, it’s not still working. That’s why, we have to activate knockout.js like this:

ko.applyBindings(new myViewModel());

What_s_knockout_js_And_First_Example_jsfiddle_net_knockout_html_paste_ViewModel_activates_knockoutJSNice work, right?🙂 We’ve just bound static data. Making the editable data is to use the value binding. Add the following HTML codes to the bottom of your HTML(View).

<p>First name: <input data-bind=”value: firstName” /></p>
<p>Last name: <input data-bind=”value: lastName” /></p>
<p>Birthdate: <input data-bind=”value: birthdate” /></p>

What_s_knockout_js_And_First_Example_jsfiddle_net_knockout_html_paste_ViewModel_activates_knockoutJSNow, run the application. And see nothing happends🙂 Don’t worry, We’re going to fix it:

That’s why, The current JavaScript code has one way which shows the data. In the fact, you edit one of the textboxes, it update viewmodel data. So, we should use observables which automatically bind text and value.

Update your ViewModel as the following codes:

this.firstName = ko.observable(“Mahmut”);
this.lastName = ko.observable(“Sozeri”);
this.birthdate = ko.observable(1989);

What_s_knockout_js_And_First_Example_jsfiddle_net_knockout_html_paste_ViewModel_activates_knockoutJS_value_bindings_observable

Now, run the application again and edit the textboxes. I think, you’d like it🙂

Define computed values

In this example, We’ll calculate the age using birthdate and show at bottom of your HTML(View). KO has a function by the name ko.computed which can compute values.

Add following markup at the bottom of your View:

<p>Age: <strong data-bind=”text: age”></strong></p>

What_s_knockout_js_And_First_Example_jsfiddle_net_knockout_html_paste_ViewModel_activates_knockoutJS_value_bindings_observable_computedValue

Next, add an age property to your JavaScript(ViewModel) and re-run the application:

this.age = ko.computed(function()
{
return new Date().getFullYear() – this.birthdate();
},this);

What_s_knockout_js_And_First_Example_jsfiddle_net_knockout_html_paste_ViewModel_activates_knockoutJS_value_bindings_observable_computedValue2

Add functionality

I want to show you with a last behavior is a button that returns you FirstName, LastName and Age on a line.

Add a fullPerson function  to your ViewModel:

this.person = ko.observable(“”);
this.fullPerson = function()
{
this.person(this.firstName() + ” ” + this.lastName() + ” ” + this.age());
};

What_s_knockout_js_And_First_Example_jsfiddle_net_knockout_html_paste_ViewModel_activates_knockoutJS_value_bindings_observable_computedValue_behavior_click

Updating View(HTML)

Just add following markup to your View:

<button data-bind=”click: fullPerson”>Show!</button>
<strong data-bind=”text: person”></strong>

What_s_knockout_js_And_First_Example_jsfiddle_net_knockout_html_paste_ViewModel_activates_knockoutJS_value_bindings_observable_computedValue_behavior_click2

That’s all, there is no big deal🙂 This was a really basic example, however it did demostrate some points of MVVM.

Download

Here is the example.

Feel free to stay in touch.

Regards

Mahmut Can Sozeri

, , , , , , , , , , , , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s