【问题标题】:Knockout JS : Function call twice timeKnockout JS:函数调用两次
【发布时间】:2018-08-28 11:04:13
【问题描述】:

我添加了一个文本框,我想在每个应该调用的 keyup 函数上都这样做。

这是我的 html 代码:

<input type="text" id="description" class="form-control" maxlength="255" data-bind="event:{keyup: doSomething},value: property1,valueUpdate:'afterkeyup'"></input>

这是我的淘汰赛js代码:

define(['uiComponent','ko'], function(Component,ko) {
         return Component.extend({
            defaults:{
                property1: ko.observable(),
                tracks: {
                        property1: true
                  }
            },
            initialize: function () {
                this._super();
            },
            getText: function () {
                return "call the function here..";
            },
            doSomething : function(){
                this.property1.subscribe(function(newValue){
                    console.log(newValue);
                    console.log("inside subscribe");
                });
            }
        });
});

例如:当我按下 T 然后它会调用一次。之后,我按 E 然后它会调用两次而不是一次。

我想在每个 keyup 上都这样做,我想获取文本框值。

怎么做?

【问题讨论】:

    标签: javascript events knockout.js event-handling dom-events


    【解决方案1】:

    有两种方式绑定订阅事件是一种“反模式”。

    initialzie 中,为您的 observable 创建一次订阅:

    initialize: function() {
      /* ... */
      this.property1.subscribe(function(newValue) { /* ... */ });
    }
    

    如果您打算稍后删除该组件,您可以存储订阅并在删除时将其丢弃。 (类似于您目前在每个活动中所做的事情。)

    现在,每当keyup 发生时,敲除从输入中读取value,将其写入property1,然后调用订阅的函数。

    【讨论】:

      【解决方案2】:

      终于,我得到了解决方案:

      我确实喜欢一种可能的解决方法是在调用 subscribe 时存储返回的 subscription 对象,如果已经存储了 subscription 存在 dispose 它 在再次订阅之前。

      define(['uiComponent','ko'], function(Component,ko) {
               return Component.extend({
                  defaults:{
                      property1: ko.observable(),
                      subscription : null,
                      tracks: {
                              property1: true
                        }
                  },
                  initialize: function () {
                      this._super();
                  },
                  getText: function () {
                      return "call the function here..";
                  },
                  doSomething : function(){
                      if (this.subscription)
                          this.subscription.dispose();
      
                      this.subscription = this.property1.subscribe(function(newValue){
                          console.log(newValue);
                          console.log("inside subscribe");
                      });
                  }
              });
      });
      

      【讨论】:

        猜你喜欢
        • 2012-05-07
        • 2018-01-03
        • 1970-01-01
        • 1970-01-01
        • 2014-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多