2015-02-24 42 views
0

我想將兩個不同的數組合併成一個泛型數組,然後使用foreach進行綁定。將兩個不同的observableArray合併爲一個敲入js

視圖模型:

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() 「allCancelled」 數組的長度[0] .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 

我在做什麼錯在這裏?

回答

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; 
}); 
+1

你有它幾乎好。但是沒有必要使用observableArray。我會編輯你的答案。 – 2015-02-24 22:35:35

+0

非常感謝你 – Saba 2015-02-25 00:37:07

+0

我向自己挑戰,讓自己更加簡潔,只是爲了好玩,感興趣,參見[link](https://jsfiddle.net/bpwLxrxx/11/) – t1nr2y 2016-12-02 18:11:17

0

您正在推送一個標準的JavaScript對象,而不是帶有可觀察對象的Knockout模型。實際上沒有理由甚至沒有這種粒度。只要做到:

self.allCancelled.push(item); 
+0

感謝您的答覆。問題是cancelledItem1和cancelledItem2是具有完全不同屬性的數組,因爲我上面提到過,所以push(item)在這裏不起作用。 – Saba 2015-02-24 20:03:09