which function will be consider as view model in knockout js

72 views Asked by At

i am new in knockout js. so please see my below code and tell me which function will be consider as view model ?

there are two function one is CartLine and other one is Cart.............which function will be consider as view model ?

see this code ko.applyBindings(new Cart());

apply binding pointing Cart function.......so does it mean cart() will be consider as view model ? if yes then what we should CartLine() ? is it child or nested view model ?

looking for guidance. code taken from this jsfiddle http://jsfiddle.net/3bu6nybk/15/

var CartLine = function () {
          var self = this;
          self.products = ko.observableArray(_products);
          self.product = ko.observable(1);
          self.price = ko.observable(1);
          self.quantity = ko.observable(1);   
          self.product.subscribe(function(item){
              if(!item)
              { 
                 self.price(0);
                 self.quantity(0);
                 return;
              }
             self.price(item.price);
             self.quantity(item.quantity);
          });

          self.subtotal = ko.computed(function () {

              return self.price() * self.quantity();
          },self);
      };

      var Cart = function () {
          // Stores an array of lines, and from these, can work out the grandTotal
          var self = this;
          self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
          self.formatCurrency = formatCurrency;

      };
1

There are 1 answers

2
TopBanana9000 On

If you enclose all of your code in a variable like this:

var viewModel = {
    //your code here
}

then call your apply bindings like so:

ko.applyBindings(new viewModel());

Everything will be in your viewmodel.

See this link for more info: http://knockoutjs.com/documentation/observables.html