Knockout.js + ES6 +下划线模板

时间:2017-04-17 00:11:28

标签: javascript knockout.js

我正在尝试使用Knockout.js创建产品购物车。每个项目都会输出加号和减号按钮以及删除按钮。我的目标是能够增加或减少增量或减少数量,并使用删除按钮删除产品。我的约束是我不能使用JQuery。

我试图分离我的应用程序问题,以便我有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'>&ndash;</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'>&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;

1 个答案:

答案 0 :(得分:0)

click绑定为回调函数提供当前$data值。但由于您正在使用Underscore作为循环,$data不是该项目。您可以将click绑定更改为以下内容:

<a href="#" data-bind="click: function() {minus(item)}" class='left-minus'>&ndash;</a>