ViewModel中的Knockout函数返回Undefined不是Function

时间:2014-11-27 01:27:39

标签: knockout.js

我跟随Knockout.js上的Succinctly系列。

我已经将他们的代码传递给了T,但我收到了一个不寻常的错误,似乎没有明显的答案。

这是我的JS:

  // create view models for Knockout

  function Product(name, price) {
    this.name = ko.observable(name);
    this.price = ko.observable(price);
  };

  function PersonViewModel() {
    this.firstName = ko.observable("Joe");
    this.lastName = ko.observable("Jesse");
    this.fullName = ko.computed(function() {
      return this.firstName() + " " + this.lastName();
    }, this);
    this.shoppingCart = ko.observable([
      new Product("Beer", 12.99),
      new Product("Wine", 29.99),
      new Product("Chips", 1.99)
    ]);
    this.addProduct = function() {
      this.shoppingCart.push(new Product("Moar Beer", 12.99));
    };
  };

  var vm = new PersonViewModel();

  ko.applyBindings(vm);

以下是我的观点:

<p data-bind="text: fullName"></p>
<table>
  <thead>
    <tr>
      <th>Product</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: shoppingCart">
    <tr>
      <td data-bind="text: name"></td>
      <td data-bind="text: price"></td>
    </tr>
  </tbody>
</table>

<div class='ui button' data-bind="click: addProduct">
  Moar Beer
</div>

我想注意KO成功显示所有数据(Joe Jesse和可观察产品数组)。但是,当我点击按钮触发addProduct()时,我收到一个&#34;未定义的不是函数&#34;。

错误明确指的是addProduct:

this.shoppingCart.push(new Product("Moar Beer", 12.99));

这里发生了什么?

1 个答案:

答案 0 :(得分:1)

shoppingCart必须是observableArray

this.shoppingCart = ko.observableArray([
  new Product("Beer", 12.99),
  new Product("Wine", 29.99),
  new Product("Chips", 1.99)
]);

  // create view models for Knockout

  function Product(name, price) {
    this.name = ko.observable(name);
    this.price = ko.observable(price);
  };

  function PersonViewModel() {
    this.firstName = ko.observable("Joe");
    this.lastName = ko.observable("Jesse");
    this.fullName = ko.computed(function() {
      return this.firstName() + " " + this.lastName();
    }, this);
    this.shoppingCart = ko.observableArray([
      new Product("Beer", 12.99),
      new Product("Wine", 29.99),
      new Product("Chips", 1.99)
    ]);
    this.addProduct = function() {
        console.log(this);
      this.shoppingCart.push(new Product("Moar Beer", 12.99));
    };
  };

  var vm = new PersonViewModel();

  ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<p data-bind="text: fullName"></p>
<table>
  <thead>
    <tr>
      <th>Product</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: shoppingCart">
    <tr>
      <td data-bind="text: name"></td>
      <td data-bind="text: price"></td>
    </tr>
  </tbody>
</table>

<div class='ui button' data-bind="click: addProduct">
  Moar Beer
</div>