Saturday, 24 August 2013

Knockout: Built in bindings

Introduction:
The Built in bindings are built into knockout and facilitate binding to attribute for elements. We can use multiple bindings separated by commas.

The text binding:
It causes the associated DOM element to display text value.

The viewmodel
var viewModel = {
         message: "text binding message"
};

The html
The message is: <span data-bind="text: message"></span>

The output
The message is: text binding message

The html binding:
It causes the associated DOM element to display HTML text.

The viewmodel
var viewModel = {
         htmlMessage: "<p>html binding message</p>"
};

The html
The message is: <span data-bind="html: htmlMessage"></span>

The output
The message is: <p>html binding message</p>

The visible binding:
It causes the associated DOM element to become hidden or visible.

The viewmodel
var viewModel = {
         isShowMessage: true
};

The html
<div data-bind="visible: isShowMessage">
    This message will be shown only when "isShowMessage" is true.
</div>

The output
This message will be shown only when "isShowMessage" is true.

The css binding:
It adds or removes css classes to the associated DOM element.

The style
.profitWarning {
          color: Red;
 }

The viewmodel
var viewModel = {
         profit: 99
};

The html
<div data-bind="css: { profitWarning: profit < 100 }">
 Profit Information
</div>

The output
Profit Information

The style binding:
It adds or removes styles to the associated DOM element.

The viewmodel
var viewModel = {
         profit: 99
};

The html
<div data-bind="style: { color: profit < 100 ? 'red' : 'black' }">
 Profit Information
</div>

The output
Profit Information

The attr binding:
It sets the value of any attribute for the associated DOM element.

The viewmodel
var viewModel = {
     url: "https://www.google.co.in",
     details: "google web site"
};

The html
<a data-bind="attr: { href: url, title: details }">Google link </a>

The output

The click binding:
It adds a click event handler to the associated DOM element.

The viewmodel
var viewModel = {
     showAlert: function() {
           alert('hi');
      }
 };

The html
<button data-bind="click: showAlert">Click me</button>

The output
It will show a button and after clicking on this button it will show alert message.

The event binding:
It allows to add an event handler for a specified event to the associated DOM element. This can be used to bind to any event, such as click,  keypress, mouseover or mouseout.

The viewmodel
var viewModel = {
      showAlert: function() {
        alert('hi');
     }
 };

The html
<div data-bind="event: { mouseover: showAlert }">
 Mouse over me
</div>

The output
It will show message "Mouse over me" and on mouse over of this it will show alert .

The submit binding:
It adds an event handler so that the javascript function will be invoked when the associated DOM element is submitted. We typically use this on form elements.

The viewmodel
var viewModel = {
     showAlert: function() {
          alert('hi');
    }
};

The html
<form data-bind="submit: showAlert">
 <button type="submit">Submit</button>
</form>

The output
It will show submit button and on click on this it will show alert .

The enable binding:
It causes the associated DOM element to be enabled when the parameter value is true. This is useful with elements like input, select and textarea.

The viewmodel
var viewModel = {
        isEnabled: false
};

The html
<input type='text' data-bind="enable: isEnabled" />

The output
It will show textbox disabled as the isEnabled is false.

The disable binding:
It causes the associated DOM element to be disabled when the parameter value is true.This is useful with elements like input, select and textarea.

The viewmodel
var viewModel = {
      isDisabled: true
};

The html
<input type='text' data-bind="disable: isDisabled" />

The output
It will show textbox disabled as the isDisabled is true.

The value binding:
It is like text binding, but the only difference is that it is a two-way binding. This is useful with elements like input, select, textarea.
-> The associated element value will be updated when viewmodel property will change.
-> When the user edits the value in the associated element, it updates the value of view model property.

The viewmodel
var viewModel = {
        userName: ko.observable("Rakesh")
};

The html
Login name: <input data-bind="value: userName" />

The output
Login Name: Rakesh

The hasFocus binding:
It is a two-way binding.
-> The associated element will become focused or unfocused according to viewmodel property is true or false.
-> The viewmodel property will be set true or false when user manually focuses or unfocuses the associated element.

The viewmodel
var viewModel = {
      isFocus: true
};

The html
<input data-bind="hasFocus: isFocus" />

The output
It will display textbox with focus as viewmodel property "isFocus" is true.

The checked binding:
It links a checkable form control(a checkbox or a radio button) with a viewmodel property.

The viewmodel
var viewModel = {
      isChecked: true
};

The html
<input type="checkbox" data-bind="checked: isChecked" />

The output
It will display checkbox with checked as viewmodel property "isChecked" is true.

The options binding:
This binding is only used with dropdownlist. It is used to populate items in dropdownlist.

The viewmodel
var viewModel = {
       availableCountries : ko.observableArray(['France', 'Germany', 'Spain'])
};

The html
<select data-bind="options: availableCountries" size="5" multiple="true"></select>

The output
It will display dropdownlist with items.

The selectedOptions binding:
It controls the selected item in dropdownlist.

The viewmodel
var viewModel = {
       availableCountries : ko.observableArray(['France', 'Germany', 'Spain']),
       chosenCountries : ko.observableArray(['Germany'])
};

The html
<select data-bind="options: availableCountries, selectedOptions: chosenCountries" size="5" multiple="true"></select>

The output
It will display dropdownlist with selected item "Germany".

The uniqueName binding:
It sets the name attribute of associated element to some unique string value if this element doesn't have name attribute.

The foreach binding:
It duplicates a section for each entry in an array.
The viewmodel
var viewModel = {
     people: [
         { firstName: 'Bert', lastName: 'Bertington' },
         { firstName: 'Charles', lastName: 'Charlesforth' },
         { firstName: 'Denise', lastName: 'Dentiste' }
     ]
};

The html
<table>
  <thead>
   <tr>
     <th>First name</th><th>Last name</th>
  </tr>
  </thead>
  <tbody data-bind="foreach: people">
   <tr>
    <td data-bind="text: firstName"></td>
    <td data-bind="text: lastName"></td>
    </tr>
   </tbody>
</table>

The output
First name        Last name
Bert                 Bertington
Charles            Charlesforth
Denise             Dentiste

The if binding:
It causes a section to appear if a specified expression evaluates to true.

The viewmodel
var viewModel = {
       displayMessage : true
};

The html
<div data-bind="if: displayMessage">
Here is a message.
</div>

The output
It shows message "Here is a message" as the viewmodel property displayMessage is true.

The ifnot binding:
It is invert of if binding.

The viewmodel
var viewModel = {
       displayMessage : true
};

The html
<div data-bind="ifnot: !displayMessage">
Here is a message.
</div>

The output
It will show message "Here is a message" as the viewmodel property displayMessage is true.

The with binding:
It  creates a new binding context, so that descendant elements are bound in the context of a specified object.
The viewmodel
var viewModel = {
      person: {
           firstName: "Rakesh", lastName: "Nayak"
      }
};
The html
</div> <p data-bind="with: coords">
 First Name: <span data-bind="text: firstName"></span>,
 Last Name: <span data-bind="text: lastName">
</span> </p>

The output
First Name: Rakesh, Last Name: Nayak

Summary:
In this blog, I explained all built in bindings in knockout.





Tuesday, 20 August 2013

Knockout: Knockout and MVVM pattern

Introduction:
Knockout.js is a javascript library that helps us to create rich and responsive use interfaces with a clean data model.

Features:
1. Declarative Bindings - A simple way to bind a part of UI to data model.
2. Dependency Tracking - Automatically updates right part of UI when data model changes.
3. Templating - A simple way to make nested UIs as a function of view model data.
4. Trivially Extensible - With a just few line of code, we can implement custom behaviors as new declarative binding for easy reuse.

Benefits:
1. Free and open source.
2. Pure javascript - works with any client side or server side technology.
3. Small and lightweight - 40kb, around 30kb after gzipping.
4. It has no dependencies.
5. It works with any mainstream browser ((IE 6+, Firefox 2+, Chrome, Safari, others).

 Knockout.js simplifies javascript UIs by applying the MVVM pattern.

What is MVVM pattern?
MVVM was originally defined by Microsoft for use with Windows Presentation Foundation (WPF) and Silverlight.

In recent years, MVVM has been implemented in JavaScript in the form of structural frameworks such as KnockoutJS, Kendo MVVM and Knockback.js.

Model-View-View Model (MVVM) is a design pattern to clearly separate the development of user-interfaces from  the business logic and behavior in an application.


A Model:
It is a set of classes representing the data comes from services or database. We usually make ajax call to some server side code to read or write the data.

A ViewModel:
It is a pure-code representation of the data and operations on a UI

We can write a View-Model just like declaring any javascript object:
var myViewModel = {
    personName: 'Rakesh',
    personAge: 123
};


A View:
A visible, interactive UI representing the state of the view model. It displays information from the view model, sends commands to the view model (e.g., when the user clicks buttons), and updates whenever the state of the view model changes.

We can write it as HTML:
The name is <span data-bind="text: personName"></span>

It will display the output as:
The name is Rakesh

Activating Knockout:
Data-bind attribute - The data-bind attribute isn’t native to HTML, though it is perfectly OK (it’s strictly used in HTML 5, and causes no problems with HTML 4 )

We need to activate knockout to make data-bind attribute effect:
ko.applyBindings(myViewModel);


If you want to bind model to a part of view:
ko.applyBindings(myViewModel, document.getElementById('someElementId'));
ko.applyBindings(myViewModel, $('#someElementId')[0]);

Summary:
In this blog I explained the features and benefits of  knockout.js and how knockout.js facilitates MVVM pattern.