【问题标题】:Knockout js doesn't apply淘汰赛js不适用
【发布时间】:2020-06-22 08:58:09
【问题描述】:

这里是初学者并尝试运行 Knockout js。 使用 debian 10。

我做了什么: -installed Knockoutjs(凉亭安装淘汰赛) - 在 Visual Studio 代码上使用了 Knockout

我的代码:

    <html>
    <head>
    <title>Knockout Test</title>
    </head>
    <body>


    <p>First name: <input data-bind="value: firstName" /></p>
    <p>Last name: <input data-bind="value: lastName" /></p>

    <p>Full name: <strong data-bind="text: fullName"></strong></p>

    <button data-bind="click: capitalizeLastName">Go caps</button>

   <script type="text/javascript" src="js/knockout-3.5.1.js"></script>
   <script type="text/javascript">

    function AppViewModel() {

        this.firstName = ko.observable("Bert");
        this.lastName = ko.observable("Bertington");
        /*
        this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();    
        }, this);

        this.capitalizeLastName = function() {
            var currentVal = this.lastName();        // Read the current value
            this.lastName(currentVal.toUpperCase()); // Write back a modified value
        };*/
    }
   </script>
</body>
</html>

这是我得到的:

【问题讨论】:

  • 你需要将构造函数的实例绑定到DOM:ko.applyBindings(new AppViewModel())

标签: html input knockout.js observable


【解决方案1】:

以@adiga 的评论为基础,并将其作为一个工作示例,这基本上就是您所追求的。

function AppViewModel() {

  this.firstName = ko.observable("Bert");
  this.lastName = ko.observable("Bertington");

  this.fullName = ko.computed(function() {
    return this.firstName() + " " + this.lastName();
  }, this);

  this.capitalizeLastName = function() {
    var currentVal = this.lastName(); // Read the current value
    this.lastName(currentVal.toUpperCase()); // Write back a modified value
  };
}
ko.applyBindings(new AppViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>

<p>Full name: <strong data-bind="text: fullName"></strong></p>

<button data-bind="click: capitalizeLastName">Go caps</button>

【讨论】:

    猜你喜欢
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2016-08-21
    • 1970-01-01
    • 2018-08-13
    • 2013-08-14
    • 1970-01-01
    相关资源
    最近更新 更多