2016-09-15 102 views
0

我有一個KnockoutJS的問題,其中$ parent綁定上下文未定義。

代碼

<div class="row"> 
    <div class="col-md-4"> 
     <div class="panel panel-info"> 
      <div class="panel-heading"> 
       <h2 class="panel-title">Products Data</h2> 
      </div> 
      <div class="panel-body"> 
       <table class="table table-striped table-bordered table-condensed" data-bind="with: ProductsViewModel"> 
        <thead> 
         <tr> 
          <th>ProductID</th> 
          <th>Product Name</th> 
          <th>Units In Stock</th> 
          <th>Action</th> 
         </tr> 
        </thead> 
        <tbody data-bind="foreach: products"> 
         <tr> 
          <td data-bind="text: $data.ProductID"></td> 
          <td data-bind="text: $data.ProductName"></td> 
          <td data-bind="text: $data.UnitsInStock"></td> 
          <td><button class="btn btn-danger btn-xs" data-bind="click: $parent.RemoveProduct">[x] delete</button></td> 
         </tr> 
        </tbody> 
       </table> 
       <button class="btn btn-large" data-bind="click: GetProducts()">Load Data</button> 
      </div> 
     </div> 
    </div> 
</div> 

和:

/// <reference path="../Scripts/knockout-3.4.0.js" /> 
/// <reference path="../Scripts/jquery-1.10.2.js" /> 

function ProductsViewModel() { 
    var self = this; 

    self.products = ko.observableArray([]); 

    self.RemoveProduct = function() { 
     bootbox.alert({ message: 'Pressed !!', size: 'small' }); 
    } 

    self.GetProducts = function() { 
     self.products.removeAll(); 

     $.getJSON('/api/products', function (data) { 
      $.each(data, function (key, value) { 
       self.products(data); 
      }); 
     }); 
    } 
} 

$(document).ready(function() { 
    ko.applyBindings(ProductsViewModel); 
}); 

所有綁定表中的正常工作,除了click事件上的按鈕,這裏的$父是不確定的結合。

如果我刪除按鈕控件,所有的數據都綁定在表格元素中。

任何想法如何解決這個問題?這是我所知的所有標準Knockout代碼。

在此先感謝。

bax2097

我已經完全移除$父固定這一點。現在都在工作。

+0

是你看到什麼具體的錯誤信息,請參閱本的jsfiddle? –

+0

這是異常消息:在行3326 未處理的異常,列21中的http://本地主機:51496 /腳本/淘汰賽3.4.0.debug.js 0x800a138f - JavaScript的運行時錯誤:無法獲取財產「未定義或空引用 RemoveProduct」我認爲,這表明$父是未定義 – bax2097

+0

使用$路線以及,$ route.ProductsViewModel.RemoveProduct,與固定同樣的結果 – bax2097

回答

0

問題

  1. 在你的HTML您在表裝訂成with: ProductsViewModel。這是不需要的。

  2. 在您的加載數據按鈕中,您沒有通過實際功能,而是立即執行,因此只需刪除()即可。

demo

+1

我試過還需要'KO .applyBindings(new ProductsViewModel);' –

相關問題