Is it possible to data-bind visible to the negation ("!") of a boolean ViewModel property?

When using an observable in an expression you need to access it as a function like:

visible: !charted()


I agree with John Papa's comment that there should be a built-in hidden binding. There are two benefits to a dedicated hidden binding:

  1. Simpler syntax, ie. hidden: charted instead of visible: !charted().
  2. Less resources, since Knockout can observe the observable charted directly, rather than creating a computed to observe !charted().

It's simple enough to create a hidden binding, though, like this:

ko.bindingHandlers.hidden = {
  update: function(element, valueAccessor) {
    ko.bindingHandlers.visible.update(element, function() {
      return !ko.utils.unwrapObservable(valueAccessor());
    });
  }
};

You can use it just like the built-in visible binding:

<i class="icon-search" data-bind="hidden: charted, click: $parent.pie_it"></i>
<i class="icon-remove" data-bind="visible: charted, click: $parent.pie_it"></i>

It's little confusing, as you have to do

visible:!showMe()

so, i did

<span data-bind="visible:showMe">Show</span>
<span data-bind="visible:!showMe()">Hide</span>
<label><input type="checkbox" data-bind="checked:showMe"/>toggle</label>​

my model is

var myModel={
    showMe:ko.observable(true)
}
ko.applyBindings(myModel);    

​ check in fiddle http://jsfiddle.net/khanSharp/bgdbm/

Tags:

Knockout.Js