Reputation: 1011
I have an observableArray and an observable as below.
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()}
]);
In one particular function , I have passed some value to self.unreadcount(), I need to update my observableArray also accordingly.How can I do that?
Upvotes: 1
Views: 2069
Reputation: 22753
I'm not sure if this is what you are after, but I've created a JSFiddle: http://jsfiddle.net/RFc3r/2/, which uses your observableArray
and allows you to update the counts per row.
Markup:
<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());
Upvotes: 1
Reputation: 8987
You can set the count1
property with the self.unreadcount
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}
]);
Or can bind the count1
property to the $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)}
]);
};
And if you need to update count1
manually; you can do that :
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);
});
}
Upvotes: 1