使用knockout映射插件绑定数据数组

时间:2013-06-05 12:07:28

标签: knockout.js knockout-mapping-plugin ko.observablearray

我有以下JSON数据:

var donutData = [ {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"topping":
    [
        { "id": "5001", "type": "None", "price": 45.00 },
        { "id": "5002", "type": "Glazed", "price": 45.00 },
        { "id": "5005", "type": "Sugar", "price": 45.00 },
        { "id": "5007", "type": "Powdered Sugar", "price": 45.00 },
        { "id": "5006", "type": "Chocolate with Sprinkles", "price": 45.00 },
        { "id": "5003", "type": "Chocolate", "price": 45.00 },
        { "id": "5004", "type": "Maple", "price": 45.00 }
    ]
   },
    { "id": "0002",
        "type": "donut",
        "name": "Lava Cake",
        "ppu": 0.65,
        "topping":
    [
        { "id": "5001", "type": "None", "price": 45.00 },
        { "id": "5002", "type": "Glazed", "price": 45.00 },
        { "id": "5005", "type": "Sugar", "price": 45.00 },
        { "id": "5007", "type": "Powdered Sugar", "price": 45.00 },
        { "id": "5006", "type": "Chocolate with Sprinkles", "price": 45.00                           },
        { "id": "5003", "type": "Chocolate", "price": 45.00 },
        { "id": "5004", "type": "Maple", "price": 45.00 }
    ]
    }

我可以使用以下内容轻松地将此数据绑定到我的HTML页面:

var DonutViewModel = function(){
donuts = ko.observableArray();

}

$(document).ready(function () {
    ko.applyBindings(DonutViewModel(donutData));
});

这是我的HTML:

 <tbody data-bind="foreach:donuts">
<tr>
    <td data-bind="text:id"></td>
    <td data-bind="text:type"></td>
    <td data-bind="text:name"></td>
    <td data-bind="text:ppu"></td>
    <td>
        <table>
            <tbody data-bind="foreach:topping">
                <tr>
                    <td data-bind="text:type"></td>
                </tr>
            </tbody>
        </table>
    </td>
     <td>
        <table>
            <tbody data-bind="foreach:topping">
                <tr>
                    <td data-bind="text:price"></td>
                </tr>
            </tbody>
        </table>
    </td>
</tr>
</tbody>

现在我想使用knockout mapping插件完成相同的操作。我尝试了以下方法:

$(document).ready(function () {
var viewModel = ko.mapping.fromJS(donutData);
ko.applyBindings(viewModel());
//ko.applyBindings(DonutViewModel(donutData));
});

这给了我一个错误 - 显然,因为我使用了data-bind =“foreach:donuts”,这在我的viewmodel中不再存在。那么我怎样才能改变我的用户界面或数据来实现这个目标呢?

此外,在使用映射插件时,假设我想在甜甜圈数据中添加新对象,我该怎么做?

1 个答案:

答案 0 :(得分:0)

在调用映射插件后,查看viewModel上的属性。看着你的json,你没有一个叫甜甜圈的房产。您可能应该首先创建您的viewmodel,然后使用映射插件来更新它:

var viewModel = DonutViewModel();
viewModel.donuts = ko.mapping.fromJS(donutData);

要向阵列添加新的甜甜圈,只需使用push:

viewModel.donuts.push(/*js representation of a donut*/);