2013-08-21 57 views
0

我有一个可观察项目和一个按钮的observableArray。 当我点击按钮启动ajax请求,我需要更新 在按钮的相同行上的线索。Knockoutjs observableArray map single value

<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

这取决于'data'看起来像从服务器获得的东西!请在调用服务url'/api/test /'时发布一些示例数据! – nemesv

回答

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; 
    } 
    } 
}; 

顺便说一句:不要不要忘记的brakets “/ api/test /”+ row.Id()因为Idobservable,如果您想要current value you have to run the function

+0

可以使用ko.mapping? – AlwaysHC

+0

尝试在我的[jsFiddle](http://jsfiddle.net/Techsolo/dvvUP/1/)没有成功。如果你在这里找到一个使用'ko.mapping'的解决方案告诉我。 – Martin

+0

非常感谢你 – AlwaysHC

相关问题