Knockout.js/visibleバインディング
< Knockout.js
ナビゲーションに移動
検索に移動
2012年4月11日 (水) 08:32時点におけるimported>Administratorによる版
Knockoutのvisibleバインディングとは、パラメーターの値に応じ、関連付けられたDOM要素を表示または非表示にする可視バインディングのひとつである。
パラメーター
false
値がfalse系の場合 (false、数字の「0」、null、undefined)の場合には、domElement.style.displayにnoneに設定し、項目を非表示にする。
true
値がtrue系(true、非nullのオブジェクト、配列)の場合には、domElement.style.displayを削除し、項目を非表示にする。
ノート
JavaScriptで動的に上書きするので、あらかじめCSSで設定したスタイルよりも優先されるので注意すること。
非表示から表示になる際は「スタイル設定の削除」なので、たとえばdivのstyle.displayにinlineを設定していると、divのstyle.displayのデフォルト値であるblockになってしまう。
Knockout/observableでない値をバインディングした場合は、バインディング適用時(Knockout/applyBindings実行時)に1回だけ更新されて以降は更新されない。
使用例
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>knockout.js - visible bindding sample 1</title>
<script type="text/javascript" src="jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="knockout-2.0.0.js"></script>
<script type="text/javascript">
jQuery(function() {
// モデル
var AppViewModel = function() {
this.shouldShowMessage = ko.observable(true);
this.showMessage = function() {
this.shouldShowMessage(true);
};
this.hideMessage = function() {
this.shouldShowMessage(false);
};
}
// バインディング適用
ko.applyBindings(new AppViewModel());
});
</script></head>
<body>
<div data-bind="visible: shouldShowMessage">
このメッセージは "shouldShowMessage" の値がtrue系の場合にのみ表示されます。
</div>
<div>
<button data-bind="click: showMessage">表示</button>
<button data-bind="click: hideMessage">非表示</button>
</div>
</body>
</html>