【问题标题】:Knockout JS Computed Observable also takes User inputKnockout JS Computed Observable 也接受用户输入
【发布时间】:2017-06-21 08:48:16
【问题描述】:

我正在将 Knockout 与 MVC Core Web 应用程序一起使用。在我的 UI 中,我有几个输入文本字段。例如 FirstName、LastName 和 FullName。

我将 FullName 设置为计算的 observable。这是我的问题。 案例 1:基于某些条件,我想使用 FirstName 和 LastName 数据来计算 FullName。 (这是示例中显示的常见情况)。

案例 2:基于某些条件,我想读取用户可以在 FullName 文本字段中输入的输入。有人可以帮助我如何做到这一点。

  function AppViewModel() {
this.firstName = ko.observable('Bob');
this.lastName = ko.observable('Smith');

if(somecondition)
this.fullName = ko.computed(function() {
    return this.firstName() + " " + this.lastName();
} else {
    return somevalueEnterned in the text box

}, 这个); }

【问题讨论】:

    标签: knockout.js observable


    【解决方案1】:

    没有理由不能将逻辑放入计算本身。为文本框绑定使用单独的 observable,然后根据您的条件返回一个或另一个。

    function AppViewModel() {
      this.firstName = ko.observable('Bob');
      this.lastName = ko.observable('Smith');
      this.textBoxValue = ko.observable('');
    
      this.fullName = ko.computed(function() {
        if(somecondition)
          return this.firstName() + " " + this.lastName();
        } else {
          return this.textBoxValue();
        }
      }, this);
    
    }
    

    【讨论】:

    • 非常感谢杰森斯帕克。这是一种 hack,但它确实有效。
    猜你喜欢
    • 2016-08-21
    • 2018-05-26
    • 2017-06-04
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多