Knockoutjs observableArray映射单值

时间:2013-08-21 09:49:22

标签: knockout.js ko.observablearray

我有一个带有可观察项目和按钮的observableArray。 当我点击按钮启动ajax请求时,我需要更新 按钮的相同行上的velues。

<div id="list" data-bind="foreach: Values">
    Name <span data-bind="text: Name"></span>
    Category <span data-bind="text: Category"></span>
    Index <span data-bind="text: $index"></span>
    Price <span data-bind="text: Price"></span>
    <a id="button" href="#" data-bind="visible: Price > 0, click: $parent.read">read data</a><br />
</div>

<script type="text/javascript">
    var TRow = function () {
        this.Id = ko.observable(0);
        this.Price = ko.observable(0);
        this.Name = ko.observable("");
        this.Category = ko.observable("");
    }

    var TList = function () {
        var self = this;
        this.Values = ko.observableArray([new TRow()]);

        this.read = function (data) {
            readdata(self, data);
        }
    }
    var List = new TList();
    ko.applyBindings(List, document.getElementById("list"));

    function readdata(vm, row) {
        $.ajax({
            type: "GET",
            url: "/api/test/" + row.Id,
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            success: function (data, textStatus, xhr) {
               //How I can update Id, Price...???
               //It's possible to use "ko.mapping.fromJS(data.Value, {}, vm);" ???
               ...

            },
            error: function (xhr, textStatus, errorThrown) {
                console.log("Error: " + textStatus + " - " + errorThrown + " - " + xhr.responseText);
            }
        });
    }
</script>

谢谢

1 个答案:

答案 0 :(得分:0)

我为您的问题制作了jsFiddle并重构了readdata方法以提供您期望的功能

function readdata(vm, row) {

  // Received sample data after calling url: "/api/test/" + row.Id(),
  var data = {Id:0,Name:"Hans",Category:1,Price: 2.2};

  for(var i = 0; i < vm.Values().length ; i++){
    if(row.Id() == data.Id){
        row.Name(data.Name);
        row.Category(data.Category);
        row.Price(data.Price);
        break;
    }
  }   
};

顺便说一下:不要忘记 “/ api / test /”+ row.Id()中的问题,因为Id是{{} 1}},如果你想要当前值,你必须运行observable