0
我想要讓我的頭部使用Knockout.js來創建產品購物車。每個項目輸出一個加號和減號按鈕以及一個刪除按鈕。我的目標是能夠正負增加或減少數量,刪除按鈕可以刪除產品。我的約束是我不能使用JQuery。Knockout.js + ES6 +下劃線模板
我試圖分開我的應用程序的關注點,以便我有ShopView,ShopModel和ShopItem(ShopItem是推送到ShopModel中的可觀察數組的個別項目)。按鈕被渲染,但是當點擊一個單獨的刪除/添加/減號按鈕並將其值記錄到控制檯時,我只能看到我的JS類,而不是要刪除或更改的單個元素。任何有識之士將不勝感激。我已經包括了裸機的關鍵零部件的片斷:
的index.html
<script type="text/html" id="itemsList">
{{ _.each(items(), function(item) { }}
<a href="#" data-bind="click: minus" class='left-minus'>–</a>
<p class="qty" data-bind="text: item.quantity"></p>
<a href="#" data-bind="click: remove" class="remove-product">Remove</a>
<a href="#" data-bind="click: plus" class='right-plus'>+</a>
{{ }) }}
</script>
<section data-bind="template: { name: 'itemsList' }" class="items-inner"></section>`
shopView.js
class shopView {
constructor() {
this.setupShop()
}
setupShop(){
this.model.items.push(new Item(97, 'cover-3', '/media/img/cover-3.jpg', 'Issue 5', 'Spring Summer 17', 1, 10));
ko.applyBindings(this.model);
}
}
module.exports = shopView
shopView.js
let ko = require('knockout');
class shopItem{
constructor (id, url, thumbnail, title, edition, quantity, price) {
this.id = ko.observable(id)(),
this.thumbnail = ko.observable(url)(),
this.title = ko.observable(title)(),
this.edition = ko.observable(edition)(),
this.quantity = ko.observable(quantity)(),
this.price = ko.observable(price)();
this.add = function(){
};
this.minus = function(){
};
}
}
module.exports = shopItem;
shopModel
店項目
class shopModel {
constructor() {
this.items = ko.observableArray([]);
this.minus = function(item){
console.log(item);
};
this.plus = function(){
};
this.remove = (item) => {
this.items.remove(item);
};
}
}
module.exports = shopModel;
爲什麼你在這個時代使用Knockout? – Stuart