在淘汰赛中将两个不同的observableArray组合成一个

时间:2015-02-24 16:41:30

标签: javascript jquery asp.net-mvc-4 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]查看“allCancelled”数组的数据和长度.firstName在控制台中返回值但是没有发生绑定,收到此错误:

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

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

你正在推动一个标准的JavaScript对象,而不是一个带有observable的Knockout模型。实际上没有理由这么细致。只是做:

self.allCancelled.push(item);

答案 1 :(得分:0)

你应该使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;
});