Computed Observable in Knockout.js

In this post we will take a look on Computed Observable in Knockout.js. Let us start with an example, you have a ViewModel


var viewModel =
 {
 name: ko.observable("G Block"),
 age: ko.observable(40)
 };

Now you want a custom message to be rendered on the view, that message will depend on other observable of ViewModel. To create that custom message you need to create a Computed Observable. Computed Observable can be created as below,

image

It takes two required parameter,

  • First parameter as function. This function will work with other observable and calculate computed observable
  • Second parameter is name of the function. If you are creating computed observable inside ViewModel then second parameter should be this

So ViewModel with computed observable is as follows,


var viewModel =
 {

name: ko.observable("G Block"),
 age: ko.observable(40),

 };

viewModel.greet = ko.computed(function () {
 return this.name()
 + " is " +
 this.age() +
 " years old";
 }, viewModel);

 ko.applyBindings(viewModel);

On View binding can be done as follows,

 


<input type="text" data-bind="value:name" />
 <input type="text" data-bind="value:age" /> <br />
 <span data-bind="text:greet" />

Few points worth knowing about computed observable

  • It gets evaluated as soon as the computed observable is created. So we may get into problem in a scenario in which computed observable is based on properties which not yet computed or initialized or loaded.
  • If computed observable is based on simple property (not observable property) then change in property will not trigger change in computed observable
  • Change in computed observable triggers if any of the observable property it is based on gets changed.

Computed observable can be created in one more ways as well. You can create ViewModel as below,


function viewModel() {
 var self = this;
 self.name = ko.observable("G Block");
 self.age = ko.observable(40);
 self.greet = ko.computed(function () {
 return self.name()
 + " is " +
 self.age() +
 " years old";
 }, this);
 };

As you notice that we have added computed observable as part of ViewModel. If you follow this way of creating ViewModel then you need to manage this explicitly. We are passing second parameter as this. Without passing it we can’t evaluate computed observable and cannot access other observable to calculate computed observable. So if you don’t pass this as second parameter, you won’t able to access this.age() and this.name(). In above scenario we are preserving this in self inside ViewModel and using self instead of this.

Writeable Computed Observable

So far we have created computed observable reading values of other observables and then returning value based of them. These observables are Read-Only Computed Observable.

You can create writeable Computed Observable as well. You wish to create writeable computed observable in following possible scenarios

  • Interpreting user input
  • Validating user input
  • Setting values of other observables on based on some logic

So let us see how we can use writeable computed observable. Let us say you have a view as below,

clip_image001

Requirements are,

  • When you change run Average should get updated.
  • Average is computed observable and based on Runs and Match

We can achieve above requirement by creating a simple ViewModel and a read only computed observable.

One of other requirement is that when you change Average, Runs should get updated. This can be done by creating a writeable observable.

Let us start with creating a ViewModel,


var playerViewModel =
 {
 name: ko.observable("Sachin T"),
 runs: ko.observable(10000),
 match: ko.observable(100)
 };

Now we need to create a writeable computed observable.


playerViewModel.average = ko.computed({
 read: function ()
 {
 var avg = this.runs() / this.match();
 return avg;
 },
 write: function (value)
 {
 var r = value * this.match();
 this.runs(r);
 },
 owner: playerViewModel
 });

To create writeable computed observable

  • You need to pass JavaScript object to ko.computed function
  • That takes options like read, write, owner etc.
  • Read property takes a function and return value based on other observable
  • Write property also take a function as input. This function take an input parameter “value”. You may wish to perform operation on value and write back resulted value to other observable.
  • You need to ViewModel as owner. This defines the reference of the key

image

In this way you can create writeable computed observable. You can bind values to View as below,


<span data-bind="text:name"></span> <br />
 Runs: <input type="text" data-bind="value:runs" /> <br />
 Match: <input type="text" data-bind="value:match" /> <br />
 Average: <input type="text" data-bind="value:average" />

Deferred Evaluation of computed observable

Before we end this post let us discuss one more concept of deferred execution of computed observable. As we discussed in beginning of this post that computed observable get evaluated at time of creation. So if it is based on observable which is not loaded at time of creation of computed observable then you might run into problem. KO gives you option to deferred execution of computed observable. You can do that by setting deferEvaluation value to true

image

We learnt in this post about Computed Observable. I hope you find this post useful. Thanks for reading.

Why we need Observable Properties in Knockout.js

In this post we will take a look on why we need observable properties in Knockout.js

Before you read further this blog post, I would recommend you to read

Setting up Visual Studio for Knockoutjs Development

Create your First MVVM based JavaScript App in two simple steps using Knockoutjs

Inbuilt Bindings in Knockout.js: Controlling Text and Appearance

MVVM is, “When View Model changes View must be notified such that UI will be refreshed automatically

image

Let us try to understand Knockout feature Automatic UI Refresh with an example,

Let us create a simple ViewModel


var viewModel =
 {
 message: "Hello World",

 };

Now create a simple View. In View we are performing value and text binding on input and span element respectively.


<input type="text" data-bind="value:message" /> <br />
 <span data-bind="text:message" /> <br />

Now on running application, you will notice that when you change value in input textbox that value is not getting refreshed automatically on view.

image

To achieve automatic UI refresh, you need to create ViewModel properties as observable properties. You can create that as following,


var viewModel =
 {
 message: ko.observable("Hello World")

 };

Essentially you need to convert normal properties of ViewModel as observable properties to achieve automatic UI refresh.

image

Now on running application you will find that UI is getting refreshed automatically. You will notice that when you change value in input textbox that value is getting refreshed automatically on view.

clip_image001

Now these are the main tasks performed by observable properties

  • Notify about changes to subscribers
  • Automatically detect dependencies
  • To update view automatically

Reading ViewModel properties

You can read ViewModel property as below,


var m = viewModel.message();
 console.log(m);

Writing ViewModel properties

You can write ViewModel property as below,


viewModel.message("whatsup")

Writing multiple observable properties

KO allow you to write multiple observable property with chained syntax. Let us say we have a ViewModel as below,


var viewModel =
 {
 message: ko.observable("Hello World"),
 greet : ko.observable(23)
 };

And you want to update both properties. You can do that using chained syntax as below,

viewModel.message("whatsup").greet(45);
 var m = viewModel.message();
 var n = viewModel.greet();
 console.log(m);
 console.log(n);

So essentially we need observable properties in KO to achieve,

  • Two way binding
  • Notify the subscribers
  • Automatic refresh UI

I hope you find this post useful. Thanks for reading.

Inheritance in Node.js

Read other posts on Node.js here

In this post we will take a look on inheritance of objects in Node.js. We will learn to use utility module to achieve inheritance in Node.js. However keep in mind that you can write plain JavaScript to achieve inheritance in Node as well. You can use Object.create() to inherit one object to another in Node.js also.

In this post we will learn to use util module to achieve inheritance in Node.js. Very first you need to import util module in your application

image

After importing util module, let us say you have an object as below,


function Student()
{

 this.name = "G Block";
 this.age = 40;
};

Just for demonstration let us add function in object using prototype,


Student.prototype.Display= function(){
 console.log(this.name + " is " + this.age + " years old");
 };

Next we are going to create ArtsStudent object which will inherit Student object.


function ArtsStudent()
{
 ArtsStudent.super_.call(this);
 this.subject = "music";
 };

util.inherits(ArtsStudent,Student);

Second line of code in ArtsStudent object is very important,

image

If you don’t call constructor of parent object as shown in above code snippet then on trying to access properties of parent object will return undefined.

In last line ArtStudent inherits Student using util.inherits() function ,

image

Next you can create instance of ArtsStudent and call function of parent object as below,


var a = new ArtsStudent();
a.Display();

Inheritance can be chained to any order. If you want you can inherit object from ArtsStudent as well. Inherited object will contain properties from both ArtsStudent and Student objects. So let us consider one more example,


function ScienceStudent()
{
 ScienceStudent.super_.call(this);
 this.lab = "Physics";
}

util.inherits(ScienceStudent,ArtsStudent);
var b = new ScienceStudent();
b.Display();

In above example ScienceStudent object inherits both Student and ArtsStudent objects. In this way you can work with inheritance in Node.js using util module. I hope you find this post useful. Thanks for reading.

Getting started with Node.js development in Visual Studio

Setup Environment on Windows machine for Node.js Development [Set up Sublime Text]

Yes you love node.js. You love event driven development and yes multi thread is old fashioned now. Your new found love is ASYNCHRONOUS. Asynchronous everything, even reading file system. As all we know Microsoft loves Developers. So in Build they decided to give node.js development support in Visual Studio 2012 and Visual Studio 2013.

In this post we will take step by step look on setting up Visual Studio for node.js development. You need to follow below steps,

Step 1

Download in install Node.js from http://nodejs.org/

Step 2

Next download and install Node.js for Visual Studio from here,

https://nodejstools.codeplex.com/releases/view/114437

You need to make sure that you select correct option to download. I am going to install Node on Visual Studio 2012.

image

After successful installation you will get below confirmation message of successful installation.

clip_image001[6]

 

After installation above said pieces you are good to go and start developing Node.js in Visual Studio. On launching Visual Studio in JavaScript language category, you will get various project templates related to Node.js

image

There are five different project templates available.

image

You can create Node.js application web based by selecting, Blank Node.js Web Application project template.

clip_image002

On successful creation of project you will get following files in project. Solution explorer will look like below,

clip_image003

server.js will contain code and entry point of application. By default server.js contains following code

clip_image002[6]

You just need to press F5 to run with debug or Ctrl+F5 to run without debugging. This default code will give you following output in browser

clip_image003[7]

And whereas debugger is listening on port 5858.

image

So we experienced that working with Node.js in Visual Studio is very smooth. You just need to press F5 to run application and can put a breakpoint and debug the code. As you see in below image that breakpoint is being hit.

image

You can find that intellisense will work as expected. This completely support intellisense for Node.js

image

Other thing you will notice that Node.js debugger support complete stack trace.

 

clip_image002[8]

 

Exporting existing Node.js project

You can create existing Node.js project from existing Node.js project by creating a project choosing template From Existing Node.js code

clip_image002[10]

On next screen you need to browse to existing project folder. You can also select files types to be included. After providing these two input click on Finish.

image

You will find existing project has been exported to new project.

In this way you can set up Visual Studio 2012 to work with Node.js development. I hope you find this post useful. Thanks for reading.

Wish you Happy New Year 2014

I wish you Happy New Year 2014. I hope you had significant 2013 and I wish that you will have even better 2014.

 

image

I had good 2013. I got opportunity to attend and present in many conferences all across globe. I hosted each month learning gathering for developers. Blogged on various technologies to educate developers.

I can summarize my work for 2013 as below.

image

 

I had awesome time hosting and organizing C-Sharpcorner Delhi Chapter. With great team, we educated many developers. Team was not only restricted to developers but extended their help to students from villages also.

clip_image002

I am committed to help you through my blog and speaking in 2014 and all coming years as well. Once again I wish you and your loved one Happy New Year.