我想將兩個不同的數組合併成一個泛型數組,然後使用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
我在做什麼錯在這裏?
你有它幾乎好。但是沒有必要使用observableArray。我會編輯你的答案。 – 2015-02-24 22:35:35
非常感謝你 – Saba 2015-02-25 00:37:07
我向自己挑戰,讓自己更加簡潔,只是爲了好玩,感興趣,參見[link](https://jsfiddle.net/bpwLxrxx/11/) – t1nr2y 2016-12-02 18:11:17