【问题标题】:knockout javascript object issue淘汰javascript对象问题
【发布时间】:2014-12-17 08:51:57
【问题描述】:

我坚持将 javascript 对象绑定到淘汰可观察数组的方法。我正在使用 asp.net。我迷失了将 ajax 调用的响应数据分配给 javascript 对象。

我的 aspx 页面

<table id="gvActivityForm" class="test">

<th class="thdata">
                TestSample
            </th>

<tbody data-bind="foreach: arraytoadd">
                    <tr>
                        <td data-bind="text: testid"></td>                           
                    </tr>
                </tbody>

</table>

<script type="text/javascript">
   var TemplateFunction = function()
      {

      var self = this;


           self.testid= ko.observable(0);
} //end 


   RealFunction = function ()

  {
   var self = this;

   self.arraytoadd = ko.observableArray([]); //Adding an array

   self.addevent = function()

   {

  self.arraytoadd.push(new TemplateFunction());

  } 
 } //end of javascript object


   objRealFunction = new realFunction();

   ko.applyBindings(objRealFunction);

我正在通过 ajax 调用获取数据。

$.ajax({                          //start ajax call for posting and getting the data back
            type: 'POST',
            url: 'PopupWebService.asmx/ReceiveandSendJobActivity',
            data: JSON.stringify({item:obj}),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {       



               for(var i=0;i<response.d.length;i++)
               {
               TemplateFunction.testid= response.d[i].TestId; //My question is how do I assign the data .I am lost here 




               }

脚本>

【问题讨论】:

    标签: asp.net knockout.js


    【解决方案1】:

    您尚未实例化您的“TemplateFunction”的任何实例

    当您的数据从您的 ajax 调用中返回时 - 使用您的 objRealFunction 对象执行以下操作:

    success: function (response) {       
    
    
               for(var i=0;i<response.d.length;i++)
               {
                  var templateFunction = new templateFunction();
                  templateFunction.testId(response.d[i].testId);
                  objRealFunction.arraytoadd.push(templateFunction)
               }
    }
    

    您还需要更新您的视图,因为此时它期望在 observableArray 的每个成员上都有一个名为 testId 的属性。

    您需要将 html 绑定更改为

    foreach: arrayToAdd().templateFunction
    

    因为您已将 testId 属性定义为 templateFunction 对象上的 ko.observable()

    【讨论】:

      【解决方案2】:

      knockout observables 被视为函数,因此为了让您设置 observable 的值,您不能使用常规赋值运算符语法,而是将新值作为参数传递给 knockout observable 函数:

       TemplateFunction.testid(response.d[i].TestId);
      

      【讨论】:

      • .它说 emplateFunction.testid 是未定义的
      • @anyone 你能推荐一下吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-30
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      相关资源
      最近更新 更多