Привязка щелчка для изменения текста

Я очень новичок в knockout.js. Я пробовал функцию, где, когда пользователь нажимает кнопку, значение изменяется. Это своего рода кнопка включения / выключения. Я сохраняю значение на бэкэнде как истинное и ложное. Любая помощь будет принята с благодарностью.

код.js

return class MyClass {

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

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

HTML-код

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

2 ответа

Решение

Вы возвращаете свою модель, не применяя привязки в своем примере кода.

Вот краткий способ сделать то, что вы хотите:

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>

class MyClass {
      constructor(){
      let self = this;
        //this is how you set the initial value for an observable.
        this.switch = ko.observable(false);
        //functions have to publicly available for the html to be able to access it.
        this.changeValue = function(tgt, evt) {
          //an observable is a function, and you access the value by calling it with empty parameters
         if (self.switch() === false) {
                //an observable's value can be updated by calling it as a function with the new value as input
                self.switch(true);
        }
        else {
          self.switch(false);
        }
      }
      }
      
    }

    //this needs to be called at the end of the js, for the bindings to be applied
    ko.applyBindings(new MyClass());
<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>

Другие вопросы по тегам