Learn knockoutJs — an intro

Arun Raj R
3 min readFeb 12, 2017

--

As a developer, How will you simplify dynamic JavaScript UIs ?

knockout is a JavaScript library that helps you to create rich, responsive display and it helps you simplify dynamic JavaScript UIs using the Model-View-ViewModel pattern. KO can also help you to implement automatic updates of the right parts of your UI whenever the data changes more simply.

So what is really a MVVM pattern?

Model–view–view-model is a software architectural pattern. that facilitates a separation of the user interface via a markup language(view) from the business logic or back-end logic(model) and the view model is a value converter meaning the view model is responsible for exposing the data objects from the model to the view.

Headline features:

  • Elegant dependency tracking — automatically updates the right parts of your UI whenever your data model changes.
  • Declarative bindings — a simple and obvious way to connect parts of your UI to your data model.

OK, how do you implement these features ?

So you are going to learn how to define a view and declarative bindings, its data and behaviour using viewmodels , and how everything stays in sync automatically. Consider the below sample example.

VIew without bindings

Consider the above code, this is a simple HTML view with out any bindings, if we run this code we can able to see the output as ‘Ben Tom’.

How to use bindings in view ?

View with bindings

Modify the <strong> elements in the view by adding data-bind attributes to display the person's name.

data-bind attributes are how Knockout lets you declaratively associate viewmodel properties with DOM elements. You just used the text binding to assign text to your DOM elements.

Now if you run this code you cannot able to see the output, for seeing the actual data we need to define a viewmodel for this view.

How to define a viewmodel ?

This is how a simple viewmodel looks like, here we have a JavaScript function containing data about the person. But since the browser doesn’t know what it means, you need to activate Knockout to make it take effect. To activate Knockout, add the

ko.applyBindings(ViewModel);

take a look at this fiddle.

So now if we run this code we can able to see the output as ‘Ben Tom’.

Additional benefits:

  1. Pure JavaScript library .
  2. Can be added on top of your existing web application.
  3. Works on any mainstream browser.
  4. Easy and Compact.
  5. Templating

--

--

Arun Raj R
Arun Raj R

Written by Arun Raj R

I’m a Full-stack Developer, Mentor, and Consultant. https://arunraj.dev/

No responses yet