1

我对 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>
4

2 回答 2

3

您无需在代码示例中应用绑定即可返回您的模型。

这是一种简洁的方法来做你想做的事:

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>

于 2018-08-01T07:40:56.760 回答
0

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>

于 2018-08-01T07:19:01.843 回答