显示knockout可观察数组的内容

时间:2014-08-15 14:05:25

标签: javascript arrays knockout.js

大家好我是java Script淘汰框架的新手,我想用knockout显示一个数组的内容,实际上我想用ajax从数据库中检索这些内容,但我决定从更简单的东西开始,是这样的:

$(document).ready(function() {

      function requestViewModel() {

          this.branchName = ko.observable();
          this.allItems = ko.observableArray({items:[{orderItemId:1,
                description:"Chocolate",
                unitCost:8.50,
                quantity:10,
                total:84.0},
                {orderItemId:2,
                description:"Milk",
                unitCost:5.0,
                quantity:10,
                total:50.0},
                {orderItemId:3,
                description:"Sugar",
                unitCost:10.0,
                quantity:20,
                total:200.0}]});

          };

      ko.applyBindings(new requestViewModel()); 

});

......这是我的HTML

 Branch Name:   <input type="text" name = "branchName">

<br><br><br><br>

 <table>
    <thead>
        <tr><th>Item id</th><th>Description</th><th>Unit Cost</th><th>Quantity</th><th>Total</th></tr>
    </thead>
    <tbody data-bind="foreach: items">
        <tr>
            <td data-bind="text: orderItemId"></td>
            <td data-bind="text: description"></td>
            <td data-bind="text: unitCost"></td>
            <td data-bind="text: quantity"></td>
            <td data-bind="text: total"></td>
        </tr>
    </tbody>
</table>

请尽可能帮助我得到错误:

“错误:初始化可观察数组时传递的参数必须是数组,或者为null或未定义。”

1 个答案:

答案 0 :(得分:2)

错误说明了一切。你需要传入一个数组而不是像这样的对象:

this.allItems = ko.observableArray([{orderItemId:1,
            description:"Chocolate",
            unitCost:8.50,
            quantity:10,
            total:84.0},
            {orderItemId:2,
            description:"Milk",
            unitCost:5.0,
            quantity:10,
            total:50.0},
            {orderItemId:3,
            description:"Sugar",
            unitCost:10.0,
            quantity:20,
            total:200.0}]);

请注意删除{items:}