【问题标题】:Observable array within observable array可观察数组中的可观察数组
【发布时间】:2014-05-04 11:08:25
【问题描述】:

我正在尝试使用 knockoutjs 创建一个股票跟踪应用程序。我有一个可观察的产品数组,我需要用户能够添加 n 天来保存每天的库存数量。

这是我当前的代码:

// Class to represent a row in the product grid
    function product(title, category, day) {
        var self = this;
        self.title = title;
        self.category = category;
        self.day = ko.observableArray([day]);
    }

    // Class to represent a day column
    function day(day, total, cost) {
        var self = this;
        self.day = day;
        self.total = ko.observable(total);
        self.cost = ko.observable(cost);
    }

    var viewModel = {
        products: ko.observableArray([
            new product("Name", "Category", new day('2', 10, 50)),
        ]),
        addProduct: function(param){
            //console.log(param);
            this.products.push(new product("Name", "Category", new day('1', 10, 50)));
        },
        removeProduct: function(product) {
            this.products.remove(product);
        }
    };

这可以正确显示数据,但现在我想创建一个函数,允许用户向表中添加另一个日期列。

我不确定我在另一个可观察数组中使用可观察数组的方法是否正确,或者是否有更好的解决方案?如果这是正确的方法,我将如何构建一个添加更多日列的函数?

TIA!

【问题讨论】:

  • 另一个 Observable 数组中的 Observable 数组没关系。你的意思是像self.addDay = function(date){elf.day.push(date);};这样的函数吗?

标签: arrays knockout.js


【解决方案1】:

您可以任意深度地嵌套 observables。

我认为您尝试从每个产品对象中添加或删除日对象。

您可以在您的产品对象上添加一个函数来添加日期对象。

 function product(title, category, day) {
        var self = this;
        self.title = title;
        self.category = category;
        self.day = ko.observableArray([day]);
        self.addNewDay = function(){ 
            self.day.push(new day());
        };
        self.removeDay = function(day){ 
            self.day.remove(day);
        };
    }

然后在 UI 中,当您绑定到第一个数组时,您可以将按钮单击绑定到 addNewDay 以添加天数,然后在每一天绑定一个删除按钮。如下所示。

 <!-- ko foreach: product -->

 <button type="button" data-bind="click: addNewDay" class="button">Add Day</button>

  <!-- ko foreach: day -->

        <div class="row">
            <div class="small-1 large-1 column">
                <button type="button" data-bind="click: $parent.removeDay" class="button round tiny">Remove</button>
            </div>

您可以将逻辑添加到您的视图模型而不是产品中,但是您可能需要使用 $root。并玩弄它以确保从正确的产品和正确的日期中删除和添加。结帐http://knockoutjs.com/documentation/binding-context.html 以查看向上移动对象图的不同上下文。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2012-04-20
    • 2015-08-11
    • 2019-06-04
    • 2019-02-25
    • 2017-11-25
    • 2015-10-05
    相关资源
    最近更新 更多