Knockout JS real time use and explanation

We will see one simple form and see how knockout js usage.

Final Result:

You can use local knockout js we have used online cdn to demonstrate.

First let’s create normal form on which we are expert. 🙂 Copy, Paste is best thing. 😉

We have our form code so now create knockout java-script.

First create javascript knockout viewModel on which we will apply binding.

Now we have basic things ready but how to use in HTML. Answer is using data-bind syntax of knockout. See below code where we have used data-bind and scope. scope define what data viewModel, it takes.

We have knockout viewModel and bind of HTML than let take first name input.

Now if you apply above code and save , it should give error in console that firstname is not defined. Because we have not defined firstname in viewModel which we had applied, in this personData. So let’s create it using ko.observable syntax.
this.firstname = ”; is normal javascript variable and this.firstname = ko.observable(); is knockout variable.

this refer to current object or function same as javascript variable scopes.

If we write, this.firstname = ko.observable(‘Coffee’); , it will populate default value of firstname Coffee. That’s how can apply pre-defined value.

We have defined firstname, lastname, fullname, email, phoneview, mobileview, phonenumber, mobilenumber as knockout observable variables.

Second we will create preview feature where we can see what we have entered in the form.

Take simple div structure.

Now same form binding, we use same viewModel personData and bind this with div so we can use it’s properties.

Use data-bind : scope and viewModel name which is personData in our case.

Now we have bind the viewModel so let’s first see email id binding.

We have simply used text binding and assigned knockout variable email to it. Thus whatever value email id input field contains it shows immediately here without any jquery of .append or .innetHtml. Cool! 😉

Next thing, we would like to show first name and last name together as full name.
For that we will use Computed Observables and declare one computed knockout variable and use that in preview form feature.

This computed observable process the function operation and return result of that operation. We have taken firstname , lastname and concat both value and return as result.
We have store that return value to fullname variable.

In Preview, we can see

Explanation of code is that, if phoneview knockout observable is true we show Yes else No.

Same way mobileview knockout observable works.

Final code : which can be copied and paste to see result. 😉

Hope you understand things available in this post.
If like efforts, Please share, comment and subscribe for future posts and inspire more.

Leave a Reply