如何从外侧淘汰js调用嵌套函数

时间:2015-06-04 15:01:32

标签: knockout.js

我正在学习淘汰赛。所以我的理解还不是很清楚。很抱歉问这个问题。

首先看代码,看看我想要实现的目标。这里是jsfiddle链接http://jsfiddle.net/tridip/vvdvgnfh/

<button data-bind="click: $root.printproduct()">Print Product</button>
<table id="table1" cellspacing="0" cellpadding="0" border="0">
    <tr>
        <th style="width:150px">Product</th>
        <th>Price ($)</th>
        <th>Quantity</th>
        <th>Amount ($)</th>
    </tr>

    <tbody data-bind='template: {name: "orderTemplate", foreach: lines}'></tbody>
</table>

<script type="text/html" id="orderTemplate">
    <tr>
        <td><select data-bind='options: products,
                               optionsText: "name",
                               optionsCaption:"--Select--",
                               value: product'>
                               </select>
        </td>

        <td>
            <span data-bind='text:price' ></span>
        </td>
        <td>
            <input data-bind='value:quantity' />
        </td>

        <td ><span data-bind='text:subtotal()'></span></td>

    </tr>
</script>    

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);

        self.printproduct = function() {
             alert('hello');
        }            
      };

      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


      };

      ko.applyBindings(new Cart());

打印产品是一个外侧按钮,但如果我需要调用CartLine中定义的功能,那我该如何访问?是不是很有可能?

感谢

1 个答案:

答案 0 :(得分:1)

你不能在循环外调用CartLine上的函数,因为它在上下文(范围)之外,你可以遵循的一种方法是在行上点击绑定,当用户点击在行中,它调用根作用域上的函数来保存对所选购物车的引用:

 <tr data-bind="click: $root.selectRow">
    <td><select data-bind='options: products,

并且Cart功能现在具有selectRow和打印功能:

  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.selectRow = function(line) {
          self.selected = line;
      }

      self.print = function() {
          if(self.selected) {
              self.selected.printproduct();
          }
      }
  };

然后打印按钮只调用委托给所选购物车的根目录上的打印功能

<button data-bind="click: $root.print">Print Product</button>

这是jsFiddle的更新 http://jsfiddle.net/omerio/vvdvgnfh/1/