Showing posts with label KnockoutJS. Show all posts
Showing posts with label KnockoutJS. Show all posts

Thursday, 24 May 2018

005 KnockoutJS template binding

Template binding  is a sophisticated way to bind a template with associated DOM  result of rendering a template. Template binding smart  to build a sophisticated  interface structure  may be repeated and nested as per the function of view model data.

There are two type of template binding


Native
templating : Native templating generally used for printing for each , if , with control flow  bindings. This type of bonding capture the HTML markup  element and use as a template rendering against data item.

String based templating : String based computing is a way to connect  to third party template. By passing model  value to the external template , inject  the templates string  to the HTML document.



Parameters

To make a template the following properties can be sent as parameter-value to template.

  • name − The ID of an element that contains the template you wish to render .
  • nodes − This represents an array of DOM nodes to be used as the template.This     is optioanl if you have also passed a nonempty value for name. 
  • data − object data will be render  via the template.
  • if − The Template will only be rendered only if this parameter expression evaluates to true.
  • foreach − To loop template in foreach format.
  • as − This is to make an alias in foreach element.
  • afterAdd, afterRender, beforeRemove − Callable functions to be executed depending on rendered DOM elements.

A Simple named template

In this example, we have used person template and the template is wrapped with script tag. To prevent the template as JavaScript execution it typed dummy is  added  in the scripted.


 
Example



<!DOCTYPE html>
<body>
           <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"
type="text/javascript"></script>

            <div data-bind="template: { name: 'person-template', data: myName }"> </div>

<script type="text/html" id="person-template">
 
        
                 
 
</script>
<script type="text/javascript">

var myViewModel = function ()
{
        this.myName = { FirstName: 'John', LastName: 'Rich' };
};

ko.applyBindings(new myViewModel());

</script>
</body>

Output :

John Rich



A Simple named template with foreach

The following is a example of foreach parameter along with template name.

Example

<!DOCTYPE html>
<body>

            <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"
type="text/javascript"></script>

<div data-bind="template: { name: 'person-template', foreach: myName }"> </div>

<script type="text/html" id="person-template">
         
         
</script>

<script type="text/javascript">

var myViewModel = function ()
{
          this.myName = [{ FirstName: 'John 1', LastName: 'Rich 1' },
                                    { FirstName: 'John 2', LastName: 'Rich 2' },
                                    { FirstName: 'John 3', LastName: 'Rich 3'}]
};
 
ko.applyBindings(new myViewModel());

</script>
</body>

Output :

John 1 Rich 1
John 2 Rich 2
John 3 Rich 3


Creating alias Using as Keyword for foreach Items

The examples for how and alias can be created with foreach.

Example



<!DOCTYPE html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"
type="text/javascript"></script>


<ul data-bind="template: { name: 'seasonTemplate', foreach: myData, as: 'season' }"></ul>
<script type="text/html" id="seasonTemplate">



  • </script>
    <script type="text/html" id="monthTemplate">
    |
    </script>
    <script>
    var viewModel = {
    myData: ko.observableArray([
    { FistName: 'John 1', LastName: 'Rich 1', Marks: [90, 100, 95] },
    { FistName: 'John 2', LastName: 'Rich 2', Marks: [89, 99, 96] },
    { FistName: 'John 3', LastName: 'Rich 3', Marks: [88, 98, 97] },
    { FistName: 'John 4', LastName: 'Rich 4', Marks: [87, 97, 98] }
    ])
    };
    ko.applyBindings(viewModel);
    </script>
    </body>

    Output :














    Using afterAdd, beforeRemove, and afterRender

    In some situation, you need some extra code  to be puted  after some event. After ad function  is invoke  when a new item is added in array

    Example

    <!DOCTYPE html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"
    type="text/javascript"></script>
    <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
    </head>
    <body>
    <div data-bind="template: {
    name: 'person-template',
    foreach: myPerson ,
    afterRender: RenderMe
    }">
    </div>
    <script type="text/html" id="person-template">
    </script>
    <script type="text/javascript">
    function viewModel() {
    this;
    this.myPerson = ko.observableArray([
    { fisrtName: 'Jonh 1', lastName: 'Rich 1' },
    { fisrtName: 'Jonh 1', lastName: 'Rich 2'},
    ])

    this.RenderMe = function (elements, data) {
    $(elements).css({ color: 'Green' });
    }
    }
    ko.applyBindings(viewModel);
    </script>
    </body>
    </html>

    Output
    Jonh 1 Rich 1
    Jonh 1 Rich 2


    Friday, 18 May 2018

    004 KnockoutJS Computed Observables

    KnockoutJS Computed Observables
           
           KnockoutJS automatically update user interface ,if there is change in viewmodel. But the question is how KnockoutJS knows that what value change. Observable is a property model which able to notify the  change in viewmodel.Computed observable is a kind of function that depend upon one or more  underline observable.If  inner observable dependency is changed , computer observable update automatically.  Below is a Syntax of computer  possible.

    this.VariableName = ko.computed(function ()

    {


    //statement  


    return // return value


    }, this);


    Example

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

     <table>
                    <tr>
                      <td>
                          Length :
                    </td>
                   <td>
                      <input data-bind="value: Length" />
                   </td>
                  </tr>
                 <tr>
                 <td>
                          Width :
               </td>
              <td>
                        <input data-bind="value: Width" />
              </td>
              </tr>
              <tr>
             <td>
                      Square Unit Value :
              </td>
             <td>
                      <input data-bind="value: sqval" />
             </td>
             </tr>
            <tr>
             <td>
                    Area :
            </td>
           <td>
                <strong data-bind="text: AreaString"></strong>=<strong data-bind="text: Area"></strong>
            </td>
           </tr>
            <tr>
           <td>
                  Price :
          </td>
          <td>
                 <strong data-bind="text: Amount"></strong>
          </td>
         </tr>
         <tr>
        <td>
        </td>
        <td>
        </td>
       </tr>
       </table>


    <script>

    <!-- "viewmodel"-- >
    function AppViewModel() 
    {
                  this.Length = ko.observable("0");
                  this.Width = ko.observable("0");
                  this.sqval = ko.observable("0");


                this.AreaString = ko.computed(function () 
           {
                      return this.Length() + "X" + this.Width();
                 }, this);

                 this.Area = ko.computed(function () 
           {
                           return this.Length() * this.Width();
                }, this);

               this.Amount = ko.computed(function () 
          {
                     return this.Length() * this.Width() * this.sqval();
             }, this);

    }

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

    </script>
    </body>

    Output :















    Here list of observable

    In the example we are  accepting  three input.





    Here are the observable  variables which was initialized by zero.

    this.Length = ko.observable("0");
    this.Width = ko.observable("0");

    this.sqval = ko.observable("0");


    Here list of Computed observable

    Here is the list of computed observable .You have noticed that we have not called this computed  observable. This computed observable fire automatically when a change is made in underlying observable variables. Computed observable are functions  specific name.



     this.AreaString = ko.computed(function () {
            ....
        }, this);

    this.Area = ko.computed(function () {
            ....
        }, this);

    this.Amount = ko.computed(function () {
            ....
        }, this);







    You have already notice,with input "Length" and "width", the area is calculated and if you input "Square Unit Value" , the price is  calculated. You have also notice that , we have not call function  When input value is changed  , the corresponding observable notify its dependencies.If underline observable changed the corresponding computed observable of the works automatically.






    Self

    You have already noticed , that the variables in viewmodels referred by this. "this" is a reference keyword which is used to collect the data from current view model.You can use self instead of this.Self hold the reference of this.
    The Below example show how self can be used instead of this.
    Example


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

    <table>
              <tr>
                 <td>
                      Length :
                </td>
                <td>
                     <input data-bind="value: Length" />
               </td>
           </tr>
          <tr>
              <td>
                 Width :
            </td>
            <td>
                 <input data-bind="value: Width" />
            </td>
         </tr>
         <tr>
              <td>
                 Area :
            </td>
            <td>
                    <strong data-bind="text: AreaString"></strong>
            </td>
         </tr>
    </table>
    <script>

    function AppViewModel() 
    {
                self = this;
                self.Length = ko.observable("0");
                self.Width = ko.observable("0");


                self.AreaString = ko.computed(function () 
           {
                      return self.Length() + "X" + self.Width();
                      }, self);
               }

             ko.applyBindings(new AppViewModel());

    </script>
    </body>


    Output :













    Pure Computed Observables

    Pure computed observables introduced in knockoutHs 3.2.0. It does not maintain subscriptions to its dependencies when it has no subscription itself. Results to prevent memory leak and provide performance over memory benefit. It also reduce computation overhead not recalculating computed observable whose value is not being observed. It has two state when it has no change it is sleeping any change it is listening state. It do simply calculation ,it will not directly modifying other object or state. Is simply Calculation and return the value. You can verify Pure computed observables.

    ko.isPureComputed — returns true for pure computed observables.


    The following are the properties in Computed Observables:

        1)ko.isComputed :
    returns true for all computed observables.    


        2)ko.isObservable :returns true for observables, observable arrays, and all computed observables.    

        3)ko.isWritableObservable :returns true for observables, observable arrays, and writable computed observables.


    Writable Computed Observables

    Generally computed observable have value that is computed from other observable, and hence it is read only. KnockoutJS offers writable computed observable. You just need to supply your own callback function. 

    Below is the example of writable computed observable.

    One can assign values to many Observables or Computed Observable properties using the chaining syntax as follows.

    myViewModel.fullName('John Reach').age(20)


    Example
     
    <!DOCTYPE html>
          <body>
               <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"
    type="text/javascript"></script>

                  <span>First Name :<input type="text" data-bind="value: firstName" /></span><br />
                  <span>Last Name :<input type="text" data-bind="value: LastName" /></span><br />Full Name : <strong data-bind="text: FullName"></strong>
    <script>


    var myViewModel = function () 
                {
                              var self = this;
                               self.firstName = ko.observable("Enter First Name");
                               self.LastName = ko.observable("Enter Last Name");
                               self.FullName = ko.computed({
                                       read: function () { return self.firstName() + ", " + self.LastName(); },
                                        write: function (value) {
                                        var nameAndTitle = value.split(', ');
                                        self.firstName(FullName[0]);
                                        self.LastName(FullName[1]);
                        }
                    });
          };

              ko.applyBindings(new myViewModel());

    </script>
    </body>

    Output :







     

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

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