Thursday, 17 May 2018

003 KnockoutJS Observables


Observable
KnockoutJs update user interface automatically  when a value is changed in Viewmodel. But the question is how KnockoutJs knows that the value have changed. Observable is a property of a model which is able to notify KnockoutJs if any value is changed in Viewmodel. Observable also can detective agencies automatically. That reduce to write extra code for specific event handling purpose. Observable do not have any impact on data binding,  observable detector changes  made in the binding variables.Observable object are actually a functions


Syntax
this.property = ko.observable();


Example
<!DOCTYPE html>
<body>
                  <script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"      type="text/javascript"></script>
                 First Name :
               <input data-bind="value: firstName" /></br>
                 <strong data-bind = "text: firstName"></strong>

<script>
function AppViewModel() {
this.firstName = ko.observable("");
}
ko.applyBindings(new AppViewModel());
</script>
</body>

Reading and writing observables

read : observable takes no parameter  to read.


AppViewModel.firstName(); 


write: a new value to a observable , pass the new value as a parameter, will change  corresponding element.



AppViewModel.firstName('John');

Multiple observable properties:  like jQuery, KnockoutJs support  Chaing. Below is the example


AppViewModel.firstName('John').lastName('Rich');

Observable Arrays
Array is a collection of objects. KnockoutJs observable can handle array. When handling a large data set, it is very important to handle an array. The observable Syntax for array is

this.YourArrayName = ko.observableArray();

observablearray only track when an item is added or removed, it if I am a change of property of any object in an array.

You can initialise  observable array also. 

Below is the syntax of the same

this.YourArrayName = ko.observableArray(['INDIA','RUSSIA','CHINA']);
 

you can read the observable array my index of the elements.


this.myValue=YourArrayName()[1];

An example of Observable Arrays


 <!DOCTYPE html>
<body>
                 <script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" type="text/javascript"></script>

 <div >
              <form data-bind="submit: addItem">
                              Please Enter Country Name:
                             <input data-bind='value: itemToAdd' />
                             <button type="submit">Add</button>
                             <p>List of Country :</p>
                       <select multiple="multiple" width="100" data-bind="options: items">
                       </select>
             </form>
</div>
<script>
var CountryList = function (items) 
      {
            this.items = ko.observableArray(items);
           this.itemToAdd = ko.observable("");
           this.addItem = function () 
      {
                     if (this.itemToAdd() != ""
               {
                              this.items.push(this.itemToAdd());
                              this.itemToAdd("");
                          }
           } .bind(this);
};

ko.applyBindings(new CountryList(["INDIA", "CHINA", "USA"]));
</script>
</body>


OutPut 




Some Important Methods Observable Array
 
  • push('value')  : Inserts a new object at the end of array.
  • Pop() :Removes the last object from the array .
  • Reverse():Reverses an array.
  • Sort():Sorts array items ascending order.
  • unshift('value'):Inserts a new object at the beginning of the array.
  • Shift():Removes the first item from the array .
  • RemoveAll():Removes all items.
  • slice(start-index,end-index):This method slices out a piece of an array. Returns the items from start-index up to end-index.
Example of Array Reverse

<!DOCTYPE html>
<body>
                  <script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" type="text/javascript"></script>

                <button data-bind = "click: ReverseMe">Reverse Array Example</button>
               <p>Array of Counry: <span data-bind = "text: CountryArray()" ></span></p>

<script>
                    function CountryList() 
           {
                              this.CountryArray = ko.observable("");
                               this.CountryArray = ko.observableArray(['INDIA', 'USA', 'UK', 'RUSSIA', 'POLAND', 'CHINA']);

                              this.ReverseMe = function () 
                 {
                                   this.CountryArray.reverse(); // reverse order
                            }
}

var em = new CountryList();
ko.applyBindings(em);
</script>
</body>

Output






Example of Array slice

<!DOCTYPE html>
<body>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" type="text/javascript"></script>
<button data-bind = "click: spliceMe">Reverse Array Example</button>
<p>Array of Counry: <span data-bind = "text: CountryArray()" ></span></p>

<script>
function CountryList() {
this.CountryArray = ko.observable("");
this.CountryArray = ko.observableArray(['INDIA', 'USA', 'UK', 'RUSSIA', 'POLAND', 'CHINA']);

this.spliceMe = function () {
this.CountryArray.splice(1, 2);
}
}

var em = new CountryList();
ko.applyBindings(em);
</script>
</body>

Output
 






Example of Array Pop

<!DOCTYPE html>
<body>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" type="text/javascript"></script>
<button data-bind = "click: spliceMe">Pop Array Example</button>
<p>Array of Counry: <span data-bind = "text: CountryArray()" ></span></p>

<script>
function CountryList() {
this.CountryArray = ko.observable("");
this.CountryArray = ko.observableArray(['INDIA', 'USA', 'UK', 'RUSSIA', 'POLAND', 'CHINA']);

this.spliceMe = function () {
this.CountryArray.pop();
}
}

var em = new CountryList();
ko.applyBindings(em);
</script>
</body>



Output
 





002 KnockoutJS First Example

KnockoutJS is based on Model-View-ViewModel (MVVM) pattern.Below is the simple example of  KnockoutJS.The application accept first name and last name and return the full name.Here we will study the different part of Model-View-ViewModel  pattern.

Example

<!DOCTYPE html>
<body>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" type="text/javascript"></script>

<table>
          <tr>
                      <td>First Name :
          </td>
                      <td><input data-bind="value: firstName" />
          </td>
          </tr>
          <tr>
          <td>Second Name :
          </td>
          <td><input data-bind="value: SecondName" />
         </td>
         </tr>
         <tr>
         <td>Your Full Name :
         </td>
         <td><strong data-bind = "text: fullname"></strong>
         </td>
         </tr>
         <tr>
         <td>
         </td>
         <td>
          </td>
          </tr>
 </table>
 <script>

<!--"viewmodel"-- >
function AppViewModel() {
           this.firstName = ko.observable("");
           this.SecondName = ko.observable("");

this.fullname = ko.computed(function () 
{
           return this.firstName() + " " + this.SecondName();
}, this);
}

// Activattion code
ko.applyBindings(new AppViewModel());

</script>
</body>


Output







The full application has several part

1.We have added  KnockoutJS CDN url ,so that we can use KnockoutJS 
  pattern in our application.We have added the link

  https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js

2.The next part is "view" part.The entire HTML code is considered as view.Html element is bind with model.

3.Two HTML element First Name,Second Name binded with a attribute "data-bind" with two variable "firstName" and "SecondName".

4.ko.observable is a technique which keeps an eye on the value changes so that it can update the associated ViewModel data.

5.There is a function ,"computed" , which perform the required task , when the variable value has changed.

6.ko.applyBindings is concept of KnockoutJS for activation of binding.A binding context is an object that holds data that you can reference from your bindings.

The KnockoutJS has three core features
  1. Observables and dependency tracking
  2. Declarative bindings
  3. Templating
  • Observables and dependency tracking
One of the advantage of KnockoutJs   update user interface  or view  when view model is changed. How can KnockoutJs no part of your view model change ? To do this, you need to declare observable, that is a model property, that notify model about the changes and can automatically detect dependencies. Hear our observed us.
  • Declarative bindings
Declarative binding  KnockoutJs full way to connect with view.



  • Templating
The template binding populate the associated Dom element with the result rendering a template. A template is a blueprint of sophisticated UI structure.



বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...