Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout if binding doesn't work with <select>

Tags:

knockout.js

Why does this work:

<!-- ko if: show -->
    <select data-bind="options: categories, optionsText: 'name', optionsCaption: 'Select', value: selected_category"></select>
<!-- /ko -->

and this doesn't:

<select data-bind="if: show, options: categories, optionsText: 'name', optionsCaption: 'Select', value: selected_category"></select>

in another words why cannot show boolean be used inside data-bind with 'if'?

like image 539
Roman Y Avatar asked May 27 '26 22:05

Roman Y


1 Answers

You can use visible binding instead to hide the select.

As for your larger question, the if binding actually physically removes all the child DOM of the element bound with if and stores it in a node cache for later retrieval. This is to prevent any further binding within those elements which might affect other document elements.

For example, in the snippet below, if you open your browser's element inspector and push the toggle button repeatedly, you'll see the browser injecting and removing the innerText of the span.

var vm = {
  show: ko.observable(true),
  toggle: function() {
    this.show(!this.show());
  }
};

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<span data-bind='if:show'>Show Me</span>
<input type='button' data-bind='click: toggle' value='Toggle' />

And per Knockout's if binding documentation:

Correspondingly, the markup within your if block can be added or removed dynamically as the result of the expression changes. data-bind attributes will be applied to a new copy of the contained markup whenever it is re-added.

like image 119
Kyle Hale Avatar answered May 31 '26 19:05

Kyle Hale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!