0

我有一个带有可观察项目和一个按钮的 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>

谢谢

4

1 回答 1

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它是一个observable,如果你想要当前值,你必须运行function.

于 2013-08-21T11:11:43.910 回答