2

我从服务器获取插件数据,需要动态创建带有多个复选框的视图模型,然后根据所选复选框及其价格汇总这些复选框。

我的视图模型如下:

var addonsData = [
    { sku: 201, name: "addon A", price: 1 }
    { sku: 201, name: "addon B", price: 2 }
    { sku: 201, name: "addon C", price: 10 }
];

function viewModel(addonsData) {
    for (var i = 0; i < addonsData.length; i++) {
      // addonsData[i] somehow add this to the viewmodel dynamically?
    }

    this.addons = addonsData;
    this.total = ko.computed(function(){
        var x = 0;
        return x;
    });
}

ko.applyBindings(new viewModel(addonsData));

非常感谢有关上述视图模型以及 HTML 视图的指导。

4

1 回答 1

2

最简单的方法是使用ko.mapping.fromJS

看看这个小提琴

var addonsData = [{
    sku: 201,
    name: "addon A",
    price: 1
}, {
    sku: 201,
    name: "addon B",
    price: 2
}, {
    sku: 201,
    name: "addon C",
    price: 10
}];

function viewModel(ad) {
    var self = this;

    var mapping = {
        create: function (item) {
            item.data.selected = ko.observable();
            return item.data;
        }
    };
    this.addons = ko.mapping.fromJS(ad, mapping);



    this.selectedItems = ko.computed(function () {
        return ko.utils.arrayFilter(self.addons(), function (item) {
            return item.selected();
        });
    });
    this.total = ko.computed(function () {
        return self.selectedItems().length;
    });

    this.totalPrice = ko.computed(function () {
        var t = 0;
        ko.utils.arrayForEach(self.addons(), function (item) {
            if(item.selected())
               t += item.price;
        });
        return t;
    });

}

ko.applyBindings(new viewModel(addonsData));

见小提琴

我希望它有所帮助。

于 2013-07-14T20:42:13.050 回答