0
我的整個代碼工作良好,然後我添加刪除功能的演示代碼。 儘管我使用$root
調用此綁定,但它給出了相同的錯誤。 我也附上我得到的錯誤的屏幕截圖。無法處理綁定foreach與無法讀取屬性
//my product class
function Product(name, price) {
this.name = ko.observable(name);
this.price = ko.observable(price);
};
//my observable array
this.shoppingCart = ko.observableArray([
new Product("milk", 10.99),
new Product("bread", 7.99),
new Product("Jam",1.39)
]);
//below is my view model
function personViewModel() {
var self = this;
firstName= ko.observable("John");
lastName = ko.observable("Smith");
checkOut = function() {
alert("Trying to Checkout");
};
fullName = ko.computed(function() {
return firstName() + " " + lastName();
})
this.addProduct = function() {
self.shoppingCart.push(new Product("Yogurt", 10.99));
};
//this method is bind with the button and producing error
this.removeProduct = function (product) {
self.shoppingCart.remove(product)
};
};
ko.applyBindings(personViewModel);
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<body>
<h1>Hello, Knockout.js</h1>
<p><span data-bind='text: fullName'></span>'s Shopping cart</p>
<button data-bind="click: checkOut">Checkout</button>
<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>
<!--below binding is breaking the script-->
<td><button data-bind="click: $root.removeProduct">Remove</button></td>
</tr>
</tbody>
</table>
<button data-bind="click: addProduct">Add Item</button>
</body>
<!-- end snippet -->
你缺少語句中的'new'的:'ko.applyBindings(personViewModel);'應該是'ko.applyBindings (new personViewModel);' – nemesv 2015-03-02 14:01:43
@nemesv如果我評論removeProduct函數和$ root.removeProduct綁定,我可以添加產品到我的購物車。我試過ko.applyBindings(new personViewModel);只有我得到的是我在視圖上的整個產品列表,但我無法添加和刪除產品,並且更改後的錯誤是「Uncaught TypeError:無法讀取屬性'刪除'未定義的」。 – satyanshu 2015-03-02 14:10:16
你的代碼相當混亂:你不會一直使用'this'和'self',並且你從幾個導致全局定義對象的地方錯過了它們。這裏有一個固定版本:http:// jsfiddle。 net/y7wrjywn/ – nemesv 2015-03-02 14:23:11