javascript - 使用 ko.utils.arrayForEach 迭代一个 observableArray

标签 javascript knockout.js

我正在尝试计算“observableArray”的“价格”字段的总和。到目前为止,我有以下代码:

(function(){

function objFeatures(name,price) {
        return {
            name: ko.observable(name),
            price: ko.observable(price),

            removeFeatures: function () {
                appViewModel.features.remove(this);
            }
        }
    }

var appViewModel = {
features: ko.observableArray([
            new objFeatures("Feature1", 20),
            new objFeatures("Feature2", 20)
        ]),

 grandTotal: ko.computed(function () {
            var total = 0;
            ko.utils.arrayForEach(this.features(), function () {
                total += this.price();
            })
            return total;
        })
};

ko.applyBindings(appViewModel);

}());

当我尝试运行它时,我在 firebug 控制台中收到一个“错误:this.features 不是一个函数”

我做错了什么?

最佳答案

Computed observables 在创建期间立即进行评估。在您的情况下,appViewModel 尚未创建,this 将不代表 appViewModel

有很多方法可以确保 this 在这种情况下是正确的。这里有两个:

  1. 在初始对象文字之外创建它:

    var appViewModel = {
       features: ko.observableArray([
           new objFeatures("Feature1", 20),
           new objFeatures("Feature2", 20)
           ])
    };
    
    appViewModel.grandTotal = ko.computed(function() {
        var total = 0;
        ko.utils.arrayForEach(this.features(), function(feature) {
            total += feature.price();
        });
    
        return total;
    }, appViewModel);
    
  2. 在函数中创建 View 模型:

    var AppViewModel = function() {
        this.features = ko.observableArray([
            new objFeatures("Feature1", 20),
            new objFeatures("Feature2", 20)
        ]);
    
        this.grandTotal = ko.computed(function() {
            var total = 0;
            ko.utils.arrayForEach(this.features(), function(feature) {
                total += feature.price();
            });
            return total;
        }, this);
    };
    
    ko.applyBindings(new AppViewModel());​
    

关于javascript - 使用 ko.utils.arrayForEach 迭代一个 observableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9351939/

相关文章:

javascript - 如何在模式关闭时通过单击关闭来停止 Vimeo 播放

javascript - D3 : How to remove tick marks at the top and bottom of Y axis

c# - 主视图模型中的绑定(bind)

javascript - 使用 knockout 预选下拉菜单不起作用

jquery - $.ajax post、knockout 和 web api

javascript - 将 html5 表导出到 Excel jquery

javascript - js文件合并为单文件制作模式。如何单独加载

javascript - Knockout Postbox 组件之间的通信 - 如何确保订阅者处于事件状态

javascript - knockout : How to program interdependence between elements of observable array

javascript - Angular 应用程序抛出错误