Skip to content

Instantly share code, notes, and snippets.

@nantekkotai
Last active December 11, 2015 11:18
Show Gist options
  • Select an option

  • Save nantekkotai/4592966 to your computer and use it in GitHub Desktop.

Select an option

Save nantekkotai/4592966 to your computer and use it in GitHub Desktop.
[knockoutjs] visibleの制御

displayのONとOFF

Webアプリでよく使うパターンといえば、displayスタイルをnoneやblockにすることで、要素の表示を制御することでしょう。
jQueryであれば以下のようになるかと。

<div id="message">
  You will see this message only when "shouldShowMessage" holds a true value.
</div>

<script type="text/javascript">
$(function(){
  $('#message').show();
  // $('#message').hide();
});
</script>

show()およびhide()メソッドで表示をコントロール出来ますが、その都度DOMオブジェクトの取得が必要になります。
knockoutではvisibleを使うことで、true/falseの切り替えで表示を変更できます。

<div data-bind="visible: shouldShowMessage">
  You will see this message only when "shouldShowMessage" holds a true value.
</div>

<script type="text/javascript">
  var viewModel = {
    shouldShowMessage: ko.observable(true) // Message initially visible
  };
  viewModel.shouldShowMessage(false); // ... now it's hidden
  viewModel.shouldShowMessage(true); // ... now it's visible again
  ko.applyBindings(viewModel);
</script>

ほらね、簡単でしょう。
このサンプルをChromeのコンソールか何かで直接値を変えてみると、即座に表示が切り替わります。
例えば以下のようにすると、

viewModel.shouldShowMessage(false);

即座に表示が消えるはずです。
内部の動きはjQueryと同じでdisplayスタイルを変更しているだけです。

条件分岐

<div data-bind="visible: shouldShowMessageCount > 5">
  You will see this message only when "shouldShowMessage" holds a true value.
</div>

<script type="text/javascript">
  var viewModel = {
    shouldShowMessageCount: ko.observable(1)
  };
  ko.applyBindings(viewModel);
</script>

visible部分に条件式を入れることも可能です。
上記の例では、shouldShowMessageCountが5以上で無ければ表示されません。
定義されている値は1なので、この例では上記文章は表示されません。
コンソールで直接値を変えて、例えば「6」とすれば表示されることでしょう。
ぜひ確認してみてください。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment