【问题标题】:Subscribe event not getting called everytime订阅事件不会每次都被调用
【发布时间】:2015-10-05 14:24:07
【问题描述】:

我有搜索屏幕,当用户导航到结果页面时,结果页面上有带有值(分钟、字符)的单选按钮。

我已经订阅了结果页面上的单选按钮点击事件,当用户点击单选按钮订阅功能时应该调用。

现在的问题是:

1)当用户第一次点击搜索按钮时,会显示结果。

2) 用户选择“分钟”单选按钮,订阅事件被调用并开始工作。

3) 用户选择后退按钮,用户被重定向到搜索屏幕。

4) 用户点击搜索按钮,显示结果。

5)用户尝试点击“字符”按钮,订阅事件没有被调用。

她是我的代码:

<div class="nmc-righttab" style="width: 60%">
    <div class="nmc-righttab" style="margin-left:20px">
        <label class="nmc-label" style="line-height:21px">@Res.Trends.DisplayResultBy</label>
    </div>
    <div class="nmc-righttab" style="width:250px">
        <div class="nmc-lefttab" style="margin-left:5px">
            <input type="radio" id="MinuRadio" name="GphInterval" value="2" data-bind="checked:GraphClick" />
        </div>
        <div class="nmc-righttab">
            <label class="nmc-label" for="MinuRadio" style="line-height:21px">@Res.Trends.Minutes</label>
        </div>
        <div class="nmc-lefttab" style="margin-left:5px">
            <input type="radio" id="CharRadio" name="GphInterval" value="3" data-bind="checked:GraphClick" />
        </div>
        <div class="nmc-righttab">
            <label class="nmc-label" for="CharRadio" style="line-height:21px">@Res.Trends.Characters</label>
        </div>
    </div></div>

JS代码:

  this.GraphClick.subscribe(function (val) {
      model.showGraphResults(true);
      model.GraphIntervalSelected(val);
      searchSpeechGraphView(speechUsage);
  }, this)

【问题讨论】:

  • 控制台有任何错误吗?你能检查一下吗
  • 我没有看到任何错误。很简单。

标签: javascript jquery knockout.js knockout-mvc


【解决方案1】:

与其将this 作为参数传递给subscribe 方法,不如将该匿名函数与this 对象绑定。像这样

JS 代码:

this.GraphClick.subscribe(function (val) {
  model.showGraphResults(true);
  model.GraphIntervalSelected(val);
  searchSpeechGraphView(speechUsage);
}.bind(this));

【讨论】:

  • 函数中没有任何内容引用this
  • @RoyJ :是的,但通常将函数绑定到目标this 对象而不是this 范围内的对象是一种好的做法。
  • @AJAYcHIGURUPATI :你能在 jsfiddle 中复制你的问题吗,jsfiddle.net
猜你喜欢
  • 2018-09-07
  • 2013-03-10
  • 2018-10-01
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 2017-06-19
  • 2019-12-04
  • 2013-04-27
相关资源
最近更新 更多