0
在這個例子中,我們有一個房子,它有很多房間,每個房間裏有很多傢俱。我希望能夠讓用戶能夠切換每個房間的傢俱(列表可以變得很長)。在點擊w/Knockout JS時隱藏並顯示特定的數組元素
其中一個挑戰就是要確保傢俱是否可見,只爲每個單獨的房間點擊按鈕。
這裏是發揮了小提琴:http://jsfiddle.net/gztmq4p6/
我的嘗試是,每個房間,對傢俱是否是可見的可觀察到的布爾值。它沒有工作,沒有給任何錯誤,或者:
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);
}
};
};
嘗試'self.areFurnituresVisible;'而不是 –
像(self.areFurnituresVisible()!)這個http://jsfiddle.net/supercool/gztmq4p6/7/。歡呼聲 –
感謝@supercool。該解決方案非常酷。 – Marcel