【问题标题】:HTML table not updating, after pushing new item to knockout observableArray将新项目推送到淘汰 observableArray 后,HTML 表未更新
【发布时间】:2015-02-07 01:25:00
【问题描述】:

我在更新 HTML UI 时遇到问题。

当文档加载并调用“getAllProducts()”时,HTML UI 会显示我的所有项目,并为“styleStatusCss”和正确的“displayName”提供正确的 css 类,问题是当我尝试用新更新的产品(产品名称或状态已更改)更新我的 observableArray,html UI 不会更新并保持不变

所以这里是正在发生的事情的快速列表:

  • getUpdatedProducts() 每 25 秒调用一次,并返回任何产品 已经更新了
  • 我检查了我的 observable 数组有多少产品:appVM.itemList.length,它确实有 100 个(如预期的那样!),我还检查了已发回的 json 产品是否有一些修改过的数据,事实上它已经改变了!
  • 然后我使用该产品 json 对象创建 javascrip obj MyProduct
  • 现在我将新创建的 javascript obj MyProduct 添加到 observablearray:appVM.itemList.push(newUpdatedProduct);
  • 1234563这个怎么可能? HTML UI 仍然显示初始加载后的数据

请看下面大部分代码

HTML

<table >
        <tbody data-bind="foreach: itemList">
            <tr>
                <td>
                    <div data-bind="css: styleStatusCss"></div>
                </td>
                <td>
                     <div data-bind="text: displayName"></div>
                </td>
            </tr>
            </tbody></table>

这里是javascript:

<script type="text/javascript">
    var appVM;
    var initializeItems = false;

    $.ajaxSetup({
        // Disable caching of AJAX responses
        cache: false
    });



    $(document).ready(function () {
        getAllProducts();

    });

    setInterval(function () {
        if (initializeItems) {
            getUpdatedProducts();
        }
    }, 25000);



  function getAllProducts() {

        var url = '@Url.Action("_AllProducts", "Home")';
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'JSON',
        })
        .success(function (result) {
            initializeItems = true;
            appVM = new AppViewModel();
            var mappedProducts = ko.utils.arrayMap(result.ItemList, function (item) {
                var con = new MyProduct(item);
                return con;
            });
            appVM.itemList = mappedProducts;
            ko.applyBindings(appVM);
        })
        .error(function (xhr, status, error) {
            alert("FATAL ERROR");
        })


  }

  function getUpdatedProducts() {
      var url = '@Url.Action("_UpdateProducts", "Home")';
      $.ajax({
          url: url,
          type: 'GET',
          dataType: 'JSON',
      })
      .success(function (result) {
          if (result.HasNewData) {
              alert("we have some data");
              alert("START COUNT: " + appVM.itemList.length); //this shows all my 100 products -> START COUNT: 100
              alert("Number of new items: " + result.ItemList.length); // i only get one product back for easy debugging
              for (index = 0; index < result.ItemList.length; ++index) { 

                  var updatedProdJson = result.ItemList[index]; //get the json for the product
                  alert("New prod json: " + objToString(updatedProdJson)); //just for debugging print out in a readable format

                  var newUpdatedProduct = new MyProduct(updatedProdJson);//create our MyProduct object (which has all properties as observable)

                  appVM.itemList.push(newUpdatedProduct); //add our new MyProduct to the list

          alert("FINAL COUNT: " + appVM.itemList.length); // --> FINAL COUNT: 101

              }
          }
      })
      .error(function (xhr, status, error) {
          alert("Error: " + status);
      })
  }





 function AppViewModel() {
      var self = this;  //so it references the viewModel object 
      self.itemList = ko.observableArray([]);

      self.doAlert = function () {
          alert("HERE");
      }
  }



   function MyProduct(data) {
       //alert("DATA: " + objToString(data));
       this.Id = ko.observable( data.Id);
       this.Name = ko.observable(data.Name);
       this.status =  ko.observable(data.Status);

       this.displayName = ko.computed(function () {
           var fullnmae = this.Id() + " " + this.Name();
           return fullnmae;

       }, this);
       this.styleStatusCss = ko.computed(function () {
           var pStatus = 'divstatusnone';
           if (this.status() === 'H')
               pStatus = 'divlowstatus';
           if (this.status() === 'D')
               pStatus = 'divhighstatus';
           return pStatus;
       },this);
   }

   function objToString (obj) {
       var str = '';
       for (var p in obj) {
           if (obj.hasOwnProperty(p)) {
               str += p + '::' + obj[p] + '\n';
           }
       }
       return str;
   }

希望有人能告诉我哪里出错了。

非常感谢,

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    在 getAllProducts 中,您将结果分配给 itemList,丢失了您的可观察数组:

    appVM.itemList = mappedProducts;
    

    你需要这样做:

    appVM.itemList(mappedProducts);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      相关资源
      最近更新 更多