KnockoutJS Observables


KnockoutJS Observables Observables are special JavaScript objects that are used widely in KnockoutJS to handle the data exchange between view-model and view. Here in this tutorial we are going to explain how observables works in KnockoutJS.


KnockoutJS Observables | Syntax | Example

KnockoutJS basically works on the following three features-

  • 1.Observables and dependency tracking – Observables plays an important in data exchange between View and View-Model. Observables takes care of dependency tracking.
  • 2.Declarative bindingsdata-bind is used in view to handle the data(update) in ViewModel.
  • 3.Templating– KnockoutJs supports templating which enables us to create rich applications.

Syntax

KnockoutJS Observables Syntax:

this.propertyName = ko.observable('value');

You can just make any property observable. ko is globally available once you include the KnockouJS library. ‘value’ will be assigned to the view model property ie. to propertyName.

Example

Now let us create very basic example to understand the observables-

KnockoutJS Observables Example:

<!DOCTYPE html>
<head>
   <title>KnockoutJS Example</title>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js" type="text/javascript"></script>
</head>
<body>
<div>
<input type="text" data-bind="value: helloText">
     <p>Hello Welcome to <span data-bind="text: helloText"><span></p>
</div>

<script>
// data model content goes here 
var ViewModel = function() {
    this.helloText = ko.observable('Tutorialsplane.com');
};
// Activate Knockout.JS
ko.applyBindings(new ViewModel());
</script>
</body>
</html>                                                                                                                

Try it »

If you run the above the example it will produce the output something like this-

If you change the input box value it will automatically update the view part.

KnockoutJS Observables Examples

Activate KnockoutJS

As we know data-bind is not predefined HTML attribute so HTML will not understand the data-bind meaning so it is necessary to activate it. You can activate KnockoutJS simply as below-

| Example:

// Activate Knockout.JS
ko.applyBindings(new ViewModelName());

Where ViewModelName is model that you want to activate.

Observables Read And Write

  • 1. Read– You can read the model property by just – myViewModel.propertyName(); Example myViewModel.personName() –
  • 2. Write– To write value you just need to pass value as parameter as – myViewModel.personName(‘Kelly’).
  • 2. Write Multiple Values– You can also write multiple values at a time simply as – myViewModel.personName(‘Kelly’).personAge(30).personCity(‘NewYork’).

Advertisements

Add Comment

📖 Read More