javascriptbuttonknockout.jsjavascript-databinding

Knockout button click binding for changing text


I am very new to knockout.js. I was trying a feature where when a user clicks a button the value is changed. Its sort of like a on/off button. I am storing the value on the backend as true and false. Any help would be greatly appreciated.

.js code

return class MyClass {

  constructor{
    self.switch = ko.observable();
  }
  changeValue(tgt, evt) {
     let self = this;

     if (self.switch ==false) {
            self.switch = on;
    }
  }
}

.html code

<button data-bind="click: changeValue">
   <span data-bind="text: switch() ? 'On' : 'Off'"></span>
</button>

Solution

  • You return your Model without applying the bindings in your code example.

    Here is a concise way to do what you want:

    class Model {
      constructor() {
        this.switch = ko.observable(false);
      }
      changeValue() {
        this.switch(!this.switch())
      }
    }
    
    ko.applyBindings(new Model());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    <button data-bind="click: changeValue">
       <span data-bind="text: $data.switch() ? 'On' : 'Off'"></span>
    </button>