If at first you don't succeed, call it version 1.0

Contact Me

Sarvesh Kushwaha
Email : sarveshkushwaha@outlook.com

Total Pageviews

Powered by Blogger.

Saturday 1 February 2014

Knockout Observables


What are Knockout Observables ? 
Lets keeping it simple , Our UI gets automatically update when the ViewModel changes.To tell KO about changes in ViewModel we used Observables. Hey hey  ... you just used term ViewModel . how will i create a ViewModel with KO ?  


Ok... Lets create it then ..its very easy to create ViewModel with KO just create a javascript object.

var ViewModel = {
                  Name: 'Sarvesh',
                  GirlFriendName: 'Hehaha'
                };
Ok , we are done with ViewModel and now how to tell changes of ViewModel to KO ? 
Answer : just make your model properties Observable like this.


var ViewModel = {
                  Name: ko.observable('Sarvesh'),,
                  GirlFriendName: ko.observable('Hehaha')
                };

Observables:
Why we created observable like function ?? 
Yuhuuuu you got the nerve darling .. Observable are actually functions .

someecards.com - Never Forget that Observables are functions even when you are drunk :)
















Lets create a Observalue , Get and Set values :

                                                                                 //initialize model property 
var viewModel= { name : ko.observable("I hate Hello World :)") };
viewModel.name("change the value"); //set the value
alert(viewModel.name()); // Get the value
  ko.applyBindings(viewModel); // Acivate the Knockout

Bind it our Viewpage : 

 
<span data-bind="text: name"></span>
<input class="form-control " data-bind="value: name" placeholder="Name" type="text" />

And Result will be : 













Code can be downloaded from my github repository  https://github.com/sarveshkushwaha/KnockoutDemo .But it would be better if you will wait till my last blog of this series ,so you can download final code from there.

But there are some more observable types , as you have mentioned in your Presentation.


  • Observable Arrays : What if we want to observer a collection of thing ?? Thats brings Observable arrays into the picture .To detect and respond to changes in collection of things ,we use observable arrays.
Note : KO does not detect and respond to each item of collection .its just use for whole collection .To detect each property we need to further make those items as observable.
Observable arrays have some very useful built in functions,which helps us a lot .

  • myObservableArray.push('Some new value') adds a new item to the end of array
  • myObservableArray.pop() removes the last value from the array and returns it
  • myObservableArray.unshift('Some new value') inserts a new item at the beginning of the array
  • myObservableArray.shift() removes the first value from the array and returns it
  • myObservableArray.reverse() reverses the order of the array
  • myObservableArray.sort() sorts the array contents.
  • myObservableArray.remove(someItem) removes all values that equal someItem and returns them as an array
  • myObservableArray.removeAll() removes all values and returns them as an array.
Example : 
We have a list of name now i want to add some name to it , it should automatically update the view .Such situation handle by Observable arrays.

View : 













<div class="col-md-12">
                                <input type="text" data-bind="value: itemToAdd" />
                                <button class="btn btn-primary btn-sm" data-bind="click: addItem">Add</button>
 
                            </div>
 
                            <div class="col-md-3" style="padding-top10px;">
                                <ul class="list-group" data-bind="foreach: items">
                                    <li class="list-group-item"><span data-bind="text: name" /></li>
                                </ul>
                            </div>

ViewModel :



//#region  Observable Arrays
    var data = [{ name: "sarvesh" }, { name: "Akshay" }, { name: "isha" }, { name: "divya" }, { name: "priya" }];
    
    var ObservableArray = {
            // data
            items: ko.observableArray(data),
            itemToAdd: ko.observable(""),

            // behaviors
            addItem: function () {
                this.items.push({ name: this.itemToAdd() });
                this.itemToAdd("");
            }
        };
    
    ko.applyBindings(ObservableArray, document.getElementById('ObservableArrayDiv')); //second parameter defines scope of model
    //#endregion
  • Computed/Dependent Observables : Dependent or computed observable are those which encapsulate one or more observables means which are dependent on one or more observable.
Note : dependent term used in previous knockout version in latest they have changed to computed .Both terms depicts same sense.

How to create Computed Observable? :

 //#region Computed Observables
    var NameModel = { firstName : ko.observable("sarvesh"), lastName : ko.observable("Kushwaha")};

    NameModel.fullName = ko.computed(function() {
        return this.firstName() + this.lastName();
    },NameModel);

    //#endregion

Computed Observables takes two parameter :

  • First take function as argument to compute the things
  • Second takes ViewModel on which the computation will be applied


Result will be : 










I hope you have learned something by reading it .Thanks .

Code is available at my git hub repository.

0 comments:

Post a Comment