我有两个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
数组的值?这样我就可以得到颜色了吗?我想我需要第二次学习,但是我不知道有什么进一步的方法来实现这一目标。 最佳答案
几乎不可能按要求回答问题,但我知道您的麻烦是什么。这是使事情更清晰的一种方法:
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());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<script type="text/html" id="itemTmpl">
<li data-bind="style: { color: color }, text: val"></li>
</script>
<div class="test" data-bind="foreach: testArr">
<strong>Demo 3, rendered:</strong><br>
First:
<ul data-bind="template: { foreach: first, name: 'itemTmpl' }"></ul>
Second:
<ul data-bind="template: { foreach: first, name: 'itemTmpl' }"></ul>
</div>