【问题标题】:Knockout.js + ES6 + Underscore TemplatingKnockout.js + ES6 + 下划线模板
【发布时间】:2017-04-17 15:39:26
【问题描述】:

我正在尝试使用 Knockout.js 创建产品购物车。每个项目输出一个加号和减号按钮以及一个删除按钮。我的目标是能够使正负递增或递减数量,以及移除产品的移除按钮。我的限制是我不能使用 JQuery。

我尝试将我的应用关注点分开,以便拥有 ShopView、ShopModel 和 ShopItem(ShopItem 是推送到 ShopModel 中可观察数组的单个项目)。按钮已呈现,但是当单击单个删除/添加/减号按钮并将其值记录到控制台时,我只能看到我的 JS 类,而不是要删除或更改的单个元素。任何见解将不胜感激。我已经包含了关键部分的基本 sn-ps:

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;

【问题讨论】:

  • 你为什么在这个时代使用 Knockout?

标签: javascript knockout.js


【解决方案1】:

click 绑定将当前的$data 值提供给回调函数。但是因为您使用 Underscore 进行循环,所以 $data 不是项目。您可以将 click 绑定更改为如下内容:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    相关资源
    最近更新 更多