我有两个observableArray
对象:
self.firstHorizontalLineArr = ko.observableArray([{color: "red", val: 0},{color: "blue", val: 1}]);
self.secondHorizontalLineArr = ko.observableArray([{color: "blue", val: 0},{color: "red", val: 1}])
有了这些,我就像这样创建一个observableArray
:
self.testArr = ko.observableArray([{first: self.firstVerticalLineArr()},{second: self.secondVerticalLineArr()}]);
但如果我现在这样做:
<div class="test" data-bind="foreach: testArr">
<div data-bind="text: $data"></div>
</div>
然后$data
仅为{object Object]
如何获取first
和second
数组的值?例如,我可以获得颜色吗?我想我需要第二次预告,但我不知道有任何进一步的方法来实现这一目标。
答案 0 :(得分:0)
按照要求回答这个问题几乎是不可能的,但我知道你的麻烦是什么。这是一种让事情更清晰的方法:
python -m pip install pygame-1.9.2a0-cp35-none-win32.whl
function ViewModel() {
var self = this;
self.firstHorizontalLineArr = ko.observableArray([{color: "red", val: 0},{color: "blue", val: 1}]);
self.secondHorizontalLineArr = ko.observableArray([{color: "blue", val: 0},{color: "red", val: 1}])
self.testArr = ko.observableArray([{first: self.firstHorizontalLineArr()},{second: self.secondHorizontalLineArr()}]);
}
ko.applyBindings(new ViewModel());
但是,我建议合并稍微不同的数组,如下所示:
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<div class="test" data-bind="foreach: testArr">
<strong>Original, but "toJSON" so you can see what it is:</strong>
<div data-bind="text: ko.toJSON($data)"></div>
<br>
<strong>Demo 1, again "toJSON" to see what's going on:</strong>
<div data-bind="foreach: !!$data.first ? $data.first : $data.second">
<span data-bind="text: ko.toJSON($data)"></span><br>
</div>
<br>
<strong>Demo 2, rendered:</strong>
<div data-bind="foreach: !!$data.first ? $data.first : $data.second">
<span data-bind="style: { color: color }, text: val"></span><br>
</div>
<hr>
</div>
function ViewModel() {
var self = this;
self.firstHorizontalLineArr = ko.observableArray([{color: "red", val: 0}, {color: "blue", val: 1}]);
self.secondHorizontalLineArr = ko.observableArray([{color: "blue", val: 0}, {color: "red", val: 1}])
self.testArr = ko.computed(function() {
return [{
first: self.firstHorizontalLineArr(),
second: self.secondHorizontalLineArr()
}];
});
//[{first: self.firstHorizontalLineArr()},{second: self.secondHorizontalLineArr()}]
}
ko.applyBindings(new ViewModel());