代码之家  ›  专栏  ›  技术社区  ›  oneMoreDeveloper

敲除按钮单击绑定以更改文本

  •  1
  • oneMoreDeveloper  · 技术社区  · 7 年前

    我对knockout.js很陌生。我正在尝试一个功能,当用户单击一个按钮时,值就会改变。有点像开/关按钮。我在后台将值存储为true和false。 任何帮助都将不胜感激。

    .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 回复  |  直到 7 年前
        1
  •  2
  •   Akrion    7 年前

    返回模型时不应用代码示例中的绑定。

    这里有一个简单的方法来做你想做的事情:

    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>
        2
  •  0
  •   Ray    7 年前

    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>