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 :







 

005 Node.js Query String

Node.js Query String

Any URL may have optional component call query string. The query string parse the webpage and can be useful to send static argument to the webpage. The query string is composed of key value pair.

Node.js contain module called querystring.
querystring module parse query get from web page URL.Here is the syntax how you will add
querystring module to your application.


var mydata = require('querystring');


The Node.js querystring module have following methods


  • stringify :stringify method serialize an object to a  query string. A query string content "&" to add more query and "=" to set query value.It is a serialization method.



    syntax:querystring.stringify(obj[, sep[, eq[, options]]])

    Example : querystring.stringify({myName: 'John', myAge: '20'})
    will result 'myName=John&myAge=20'
  • parse :Parse do parse , just  opposite of stringify. Parts deserialize query to object.
    syntax:querystring.parse(str[, sep[, eq[, options]]])

    Example :querystring.parse('myName=John&myAge=20')
   
will result {myName: 'John', myAge: '20'}
  • escape :The escape method performs encoding of URL percent-encoded characters on the given string. It generates a URL safe string. 
    syntax:querystring.escape(str)

     Example : querystring.escape('Date of Borth 30-03-2018 at 4.30 AM')
    will result Date%20of%20Borth%2030-03-2018%20at%204.30%20AM'


  • unescape :The usescape method performs decoding of URL percent-encoded characters on the given string. 
    syntax:querystring.unescape(str)


Example : querystring.unescape(
'Date%20of%20Borth%2030-03-2018%20at%204.30%20AM');

    will result 'Date of Borth 30-03-2018 at 4.30 AM'


Query String Example


Example 1(stringify)
var querystring = require('querystring');
var q=querystring.stringify({myName:'John',myAge:20}); 
console.log(q);



Output:
myName=John&myAge=20

Example 2 (Parse)
var querystring = require('querystring');
var q = querystring.parse('myName=John&myAge=20');
console.log("Name :"+q.myName);
console.log("Age :"+q.myAge);



Output:
Name :John
Age :20




Example 3 (escape)
var querystring = require('querystring');
var q=querystring.escape('Date of Borth 30-03-2018 at 4.30 AM'); 
console.log(q); 



Output:(URL Safe string)
Date%20of%20Borth%2030-03-2018%20at%204.30%20AM



Example 4 (unescape)
var querystring = require('querystring');var q=querystring.unescape('Date%20of%20Borth%
2030-03-2018%20at%204.30%20AM'); 
console.log(q); 


Output:(URL Safe string to original string)
Date of Borth 30-03-2018 at 4.30 AM

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

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