Reputation: 7485
In this example, we have a House which has many Rooms, and each Room has many Furnitures in it. I want to be able to give the user the ability to toggle the visibly of each Room's Furnitures (the lists can get very long).
One of the challenges is making sure that the Furniture is visible or not, only for each individual room where they have clicked the button.
Here is a fiddle to play with: http://jsfiddle.net/gztmq4p6/
My attempt was to, for each Room, have an observable boolean on whether or not the Furnitures were visible. It didn't work, and wasn't giving any errors, either:
HTML
<tbody data-bind="foreach: rooms">
<tr class="well">
<td valign="top">
<input type="text" data-bind='value: name' />
// Added this
<div> <button class="btn btn-xs btn-info" data-bind='click: toggleFurnitureVisibility'>Toggle Furniture Visibility</button>
<button class="btn btn-xs btn-danger" data-bind='click: $root.removeRoom'>Remove Room</button>
</div>
</td>
<td>
// Added this
<table data-bind="visible: areFurnituresVisible">
<tbody data-bind="foreach: furnitures">
<tr>
<td>
<input type="text" data-bind='value: name' />
</td>
<td>
<input type="text" data-bind='value: size' />
</td>
<td>
<button class="btn btn-xs btn-danger" data-bind='click: $parent.removeFurniture'>Delete Furniture</button>
</td>
</tr>
</tbody>
</table>
<button class="btn btn-success btn-xs" data-bind='click: addFurniture'>Add Furniture</button>
JavaScript
var Room = function(name, furnitures) {
var self = this;
// Default to true
self.areFurnituresVisible = ko.observable(true);
self.toggleFurnitureVisibility = function (room) {
if (self.areFurnituresVisible) {
self.areFurnituresVisible = ko.observable(false);
} else {
self.areFurnituresVisible = ko.observable(true);
}
};
};
Upvotes: 0
Views: 1315
Reputation: 3938
If you have observable:
this.o = ko.observable();
and you want to update observable value you need to use syntax:
this.o(newValue);
In your case it's
self.areFurnituresVisible(!self.areFurnituresVisible());
See working fiddle
Upvotes: 1