user1400915
user1400915

Reputation: 1943

knockout js variable setting similar to calling a function

I have a variable called enable which I assign that way:

var enable = ko.observable();

In a method I am setting its value as :

enable(false);

and If I do

enable = false;

then if I see the value of enable in console , the value is not set. What is the reason for this?

Upvotes: 0

Views: 51

Answers (1)

Regis Portalez
Regis Portalez

Reputation: 4860

knockout observables are functions, as such you set their values by invoking them on the desired value:

myObservable(myValue);

Which is explained by the following quote:

"Not all browsers support JavaScript getters and setters (* cough * IE * cough *), so for compatibility, ko.observable objects are actually functions."

If you set them directly to the value, you override them and they are no longer observables, which breaks everything.

Have a look on this fiddle:

var myVM = (function() {
  var showobservable1 = ko.observable(true);
  var showobservable2 = ko.observable(true);
  return {
    show1: showobservable1,
    show2: showobservable2,
    ok: function() {
      showobservable1(!showobservable1());
    },
    broken: function() {
      showobservable2 = !showobservable2;
    }
  }
}());

ko.applyBindings(myVM);
div {
  width: 100px;
  height: 40px;
  margin-top: 10px;
  background-color: yellow;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div id="1" data-bind="visible: show1">1</div>
<div id="2" data-bind="visible: show2">2</div>
<div id="ok" data-bind="click: ok">works</div>
<div id="broken" data-bind="click: broken">break</div>

Upvotes: 1

Related Questions