【问题标题】:which function will be consider as view model in knockout js哪个函数将被视为淘汰赛js中的视图模型
【发布时间】:2015-08-19 06:35:48
【问题描述】:

我是淘汰赛 js 的新手。所以请看我下面的代码并告诉我哪个函数将被视为视图模型?

有两个函数,一个是CartLine,另一个是购物车............哪个函数将被视为视图模型?

查看此代码ko.applyBindings(new Cart());

应用绑定指向购物车功能.......那么这是否意味着cart() 将被视为视图模型?如果是,那么我们应该CartLine() 做什么?它是子视图模型还是嵌套视图模型?

寻求指导。代码取自这个 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;

      };

【问题讨论】:

  • 您的视图模型是您作为参数传递给applyBindings() 方法的对象。
  • @haim770 如果看到我发布的代码,那么你可以看到有两个函数叫做CartLine & Cart 。所以我的问题是哪个函数将被称为视图模型?两者都将被视为视图模型或将参数传递给 ko.applyBindings() 函数的模型?

标签: knockout.js


【解决方案1】:

如果您将所有代码包含在这样的变量中:

var viewModel = {
    //your code here
}

然后像这样调用您的应用绑定:

ko.applyBindings(new viewModel());

一切都将在您的视图模型中。

查看此链接了解更多信息:http://knockoutjs.com/documentation/observables.html

【讨论】:

  • 你只是不明白我的问题。假设我有很多对象字面量,比如var viewModel = { //your code here },那么哪一个会被视为视图模型?
  • 无论你“应用绑定”是什么,都是你的视图模型。 Viewmodel 是一个术语,表示模型和视图(服务器和客户端)之间的桥梁。
猜你喜欢
  • 2015-04-01
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 1970-01-01
  • 2013-01-26
  • 2016-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多