【问题标题】:Using Knockout, How do I trigger a function based on an arbitrary value of an observable value?使用 Knockout,如何根据可观察值的任意值触发函数?
【发布时间】:2012-06-11 18:17:38
【问题描述】:

我是 Knockout 的新手,尽管我以前使用过可观察模式库,但我不知道如何设置函数来观察 ViewModel 中的值并在该值发生变化时触发。

情况是这样的: 当下拉列表的值为“其他”时,我希望启用模式弹出窗口。我正在使用 Twitter 引导程序“下拉列表”(实际上是一个锚点列表),每个锚点都有一个 click 绑定到 ViewModel 上一个名为 setDetail 的函数。 setDetail 设置名为problem 的可观察属性的值。

我的想法是放一个函数来观察problem的值,以保持逻辑分离。有没有办法做到这一点,或者我应该把代码放在setDetail 函数中?

感谢任何帮助!

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    是的,您可以显式订阅 observable。

    文档是available here,搜索Explicitly subscribing to observables。

    你会做这样的事情:

    function ViewModel() {
      this.problem = ko.observable();
      this.problem.subscribe(function(newValue) {
        if (newValue === 'other') {
          // trigger modal
        }
      });
    }
    

    【讨论】:

      【解决方案2】:

      这里有一个方法,给定 HTML

      <div> 
          <select data-bind="options: dropdownOptions, selectedOptions: problem" ></select>        
      </div>
      

      还有 javascript..

      var ViewModel = function() {
          var self = this;
          this.problem = ko.observable();
          this.dropdownOptions = ko.observableArray(["1","2","3","other"]);                        
      
          this.problem.subscribe((function(selectedOption) {
              if(selectedOption == "other") {
                  alert(self.problem());            
              }
          }));
      }
      
      ko.applyBindings(new ViewModel());
      ​
      

      或小提琴:http://jsfiddle.net/keith_nicholas/pb5ja/2/

      【讨论】:

      • 感谢您的回答,这在我使用 &lt;select&gt; 的情况下会有所帮助,但在这种情况下,我使用的是 Twitter Bootstrap“下拉菜单”,它是锚点列表。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 2019-01-30
      • 1970-01-01
      相关资源
      最近更新 更多