1

下面的代码对我有用

<div id="TickerBox" style="float: right;">
    Newly Added Customer  :<span data-bind="text: lastCustomer"></span><br />
    Newly Added Product   :<span data-bind="text: lastProduct"></span><br />
    Newly Added Company   :<span data-bind="text: lastCompany"></span><br />
    Total No of Customers :<span data-bind="text: customerCount"></span><br />
    Total No of Products  :<span data-bind="text: productCount"></span><br />
    Total No of Companies :<span data-bind="text: companyCount"></span><br />
</div>

<script type="text/javascript">
    var myViewModel =
        {
            lastCustomer: ko.observable(''),
            lastProduct: ko.observable(''),
            lastCompany: ko.observable(''),
            productCount: ko.observable(0),
            customerCount: ko.observable(0),
            companyCount: ko.observable(0)
        }

    ko.applyBindings(myViewModel, document.getElementById('TickerBox'));

    $.getJSON('/api/product', function (data) {
        myViewModel.companyCount(data.companyCount);
        myViewModel.customerCount(data.customerCount);
        myViewModel.productCount(data.productCount);
        myViewModel.lastCompany(data.lastCompany);
        myViewModel.lastCustomer(data.lastCustomer);
        myViewModel.lastProduct(data.lastProduct);
    });
</script>

但是我想制作一个 ViewModel ,它可以在调用 AJAX 请求时直接与 JSON 对象绑定。不是每次都分配每个可观察的值,而是可以将 ViewModel 优化为一个集合吗?

4

1 回答 1

4

你看过淘汰赛映射插件吗?

你像这样使用它:

var viewModel = ko.mapping.fromJSON(data);

在您的 getJSON 成功函数中。

于 2013-03-26T11:36:04.063 回答