我有一个observableArray和一个可观察的如下。
self.unreadcount = ko.observable();
self.searchFilters = ko.observableArray([
{label: "A", active: ko.observable(false), count1: self.unreadcount()},
{label: "B", active: ko.observable(false), count1: self.unreadcount()},
{label: "C", active: ko.observable(false), count1: self.unreadcount()}
]);
在一个特定的函数中,我已将一些值传递给self.unreadcount(), 我也需要相应地更新我的observableArray。我怎么能这样做?
答案 0 :(得分:1)
您可以使用count1
observable设置self.unreadcount
属性。
self.searchFilters = ko.observableArray([
{label: "A", active: ko.observable(false), count1: self.unreadcount},
{label: "B", active: ko.observable(false), count1: self.unreadcount},
{label: "C", active: ko.observable(false), count1: self.unreadcount}
]);
或者可以将count1
属性绑定到$parent.unreadcount
:
<div data-bind="foreach : searchFilters">
<span data-bind="text : label"></span>
<span data-bind="text : $parent.unreadcount"></span>
<br/>
</div>
JS
var VM = function () {
var self = this;
self.unreadcount = ko.observable();
self.searchFilters = ko.observableArray([
{label: "A", active: ko.observable(false)},
{label: "B", active: ko.observable(false)},
{label: "C", active: ko.observable(false)}
]);
};
如果您需要手动更新count1
;你可以这样做:
self.searchFilters = ko.observableArray([
{label: "A", active: ko.observable(false), count1: ko.observable(self.unreadcount())},
{label: "B", active: ko.observable(false), count1: ko.observable(self.unreadcount())},
{label: "C", active: ko.observable(false), count1: ko.observable(self.unreadcount())}
]);
self.update = function(newValue) {
ko.utils.arrayForEach( self.searchFilters(), function(row) {
row.count1(newValue);
});
}
答案 1 :(得分:1)
我不确定这是不是你所追求的,但我创建了一个JSFiddle:http://jsfiddle.net/RFc3r/2/,它使用你的observableArray
并允许你更新每行的计数。
标记:
<p data-bind="text: ko.toJSON(searchFilters)"></p>
<div class="liveExample" data-bind="foreach: searchFilters">
<p>Label:<input data-bind="value: label"></input></p>
<p>Active:<input type="checkbox" data-bind="checked: active"></input></p>
<p>Unread:<input data-bind="value: count1"></input></p>
<input type="button" data-bind="click: changeValue(count1)" value="click me"/>
<hr/>
</div>
JS:
var ViewModel = function () {
self.unreadcount = ko.observable(0);
self.searchFilters = ko.observableArray([{
label: "A",
active: ko.observable(false),
count1: ko.observable(self.unreadcount())
}, {
label: "B",
active: ko.observable(true),
count1: ko.observable(self.unreadcount())
}, {
label: "C",
active: ko.observable(false),
count1: ko.observable(self.unreadcount())
}]);
self.changeValue = function(item){
item(item() + 1);
};
};
ko.applyBindings(new ViewModel());