在knockout js中将两个不同的observableArray合并为一个

Combining two different observableArray into one in knockout js

我正在尝试将两个不同的数组组合成一个通用数组,然后使用 foreach 将其绑定。

查看模型:

  self.cancelledItem1 = ko.computed(function () {
        return ko.utils.arrayFilter(self.items(), function (item) {
            return (item.category() == 'Cancelled');
        });
    });

   self.cancelledItem2 = ko.computed(function () {
        return ko.utils.arrayFilter(self.differntitems(), function (item2) {
            return (item2.status() == 'Cancelled');
        });
    });

    self.allCancelled = ko.observableArray();

    self.combineCancelled = function () {
            ko.utils.arrayForEach(self.cancelledItem1(), function (item) {
                self.allCancelled.push({
                    firstName: item.firstName(),
                    lastName: item.lastName()
                });
            });

            ko.utils.arrayForEach(self.cancelledItem2(), function (item2) {
                self.allCancelled.push({
                    firstName: item2.fName(),
                    lastName: item2.lName()
                });
            });
    }

cshtml:

    $(function () {
           var myViewModel = new MyViewModel(@Html.Raw(Model.ToJson()));
           debugger;
           myViewModel.combineCancelled();
          ko.applyBindings(myViewModel);
        }

  <div data-bind="template: {name: 'cancelled-template', foreach: allCancelled }"></div>
  <script type="text/html" id="cancelled-template">
      <div>     
         <div class="header">
            <span data-bind="text:firstName"></span>
            <span data-bind="text:lastName"></span>
         </div>
      <div  class="details">
          .
          .
          .
      </div>
 </script>

我可以使用调试器和 myViewModel.allCancelled()[0].firstName returns 控制台中的值查看 "allCancelled" 数组的数据和长度,但绑定没有发生,出现此错误:

Uncaught ReferenceError: Unable to process binding "template: function (){return {name:'cancelled-template',foreach:allCancelled} }"
Message: Unable to process binding "text: function (){return firstName }"
Message: firstName is not defined

我这里做错了什么?

您推的是标准 JavaScript 对象,而不是带有可观察对象的 Knockout 模型。实际上没有理由去这么细化。只是做:

self.allCancelled.push(item);

您应该使 allCancelled 成为计算可观察对象:

self.allCancelled = ko.computed(function () {
    var tempAllCancelled = [];

    ko.utils.arrayForEach(self.cancelledItem1(), function (item) {
        tempAllCancelled.push({
            firstName: item.firstName(),
            lastName: item.lastName()
        });
    });

    ko.utils.arrayForEach(self.cancelledItem2(), function (item) {
        tempAllCancelled.push({
            firstName: item.fName(),
            lastName: item.lName()
        });
    });

    return tempAllCancelled;
});