Reputation: 542
all! I have the following HTML:
<table>
<thead>
<tr>
<th>Simple app</th>
</tr>
</thead>
<tbody data-bind="foreach: tests">
<tr>
<td data-bind="text: testName"></td>
<td data-bind="text: result"></td>
<td><button data-bind="click: runTest, style: {backgroundColor: color}">Run test</button></td>
</tr>
</tbody>
</table>
and the following js:
function Test(testName, test) {
var vm = {};
vm.result = ko.observable(false);
vm.testName = testName;
vm.color = ko.computed(function (){
return vm.result === true ? 'green' : 'red';
}, vm);
vm.test = test;
vm.runTest = function () {
var result = vm.test();
vm.result(result);
}
return vm;
}
function TestsViewModel(modelName, tests) {
var vm = {};
vm.modelName = modelName;
vm.tests = [];
for(var i = 0; i < tests.length; i++){
vm.tests.push(Test(tests[i].title, tests[i].test));
}
return vm;
}
function test1() {
return true;
}
function test2(){
return false;
}
function test3(){
return void (0) === undefined;
}
ko.applyBindings(TestsViewModel('Name', [{
title: 'Test1',
test: test1
}, {
title: 'Test2',
test: test2
}, {
title: 'Test3',
test: test3
}]));
I want to change color of button depending on the value of result property. But knockout doesn't check the value when result was changed. What is the problem?
Upvotes: 0
Views: 62
Reputation: 3254
Inside of your computed "color" you have to use the result as an observable not just as a property. vm.result*()* not vm.result.
vm.color = ko.computed(function (){
return vm.result() === true ? 'green' : 'red';
}, vm);
Upvotes: 2
Reputation: 7602
You missed the parenthesis:
vm.color = ko.computed(function (){
return vm.result() === true ? 'green' : 'red'; // vm.result()
}, vm);
Upvotes: 4