Knockout.js:在未分配的绑定上调用函数

时间:2017-04-07 17:29:35

标签: knockout.js

这是我的第一篇文章。 我很擅长淘汰并尝试一个基本的例子。 在下面例如:我正在尝试将 ONLY 标签更改为大写标签(姓氏和全名)而不是输入文本框。所以,我最初将文本框的值分配给隐藏字段,并从那里操纵隐藏字段。但是,最后输入也修改为大写。任何帮助深表感谢!!

我的观点:

    <p>First name: <input data-bind="value: firstName" /></p>
    <p>Last name: <input data-bind="value: lastName" /></p>
    <input style="display:none;" data-bind="value: hdnlastName" />
    <p>First name: <strong data-bind="text: firstName">todo</strong></p>
    <p>Last name: <strong data-bind="text: hdnlastName">todo</strong></p>
    <p>Full name: <strong data-bind="text: firstHdnLastName"></strong></p> 
    <button data-bind="click: capitalizeHdnLastName">Click Me!!</button>

查看型号:

    function AppViewModel() {
    this.firstName = ko.observable("Gireesh");
    this.lastName = ko.observable("");

    this.hdnlastName = this.lastName;

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

    this.capitalizeHdnLastName = function(){
    var tempValue = this.hdnlastName();
    return this.hdnlastName(tempValue.toUpperCase());};
    }

1 个答案:

答案 0 :(得分:0)

目前你正在设置hdnlastName = lastName,因此两个变量都指向同一个东西。如果没有更新另一个,则无法更新。要修复它,你需要使hdnlastName成为自己的可观察

this.hdnlastName = ko.observable("");

但是你还需要让它与lastName

的更改保持同步
this.lastName.subscribe(function(value){ 
    this.hdnlastName(value);
}, this);

示例:

function AppViewModel() {
    this.firstName = ko.observable("Gireesh");
    this.lastName = ko.observable("");

    this.hdnlastName = ko.observable("");
    this.lastName.subscribe(function(value){ 
        this.hdnlastName(value);
    }, this);

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

    this.capitalizeHdnLastName = function(){
      var tempValue = this.hdnlastName();
      this.hdnlastName(tempValue.toUpperCase());
    };
}
  
ko.applyBindings(new AppViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>First name: <input data-bind="value: firstName" /></p>
    <p>Last name: <input data-bind="value: lastName" /></p>
    <input style="display:none;" data-bind="value: hdnlastName" />
    <p>First name: <strong data-bind="text: firstName">todo</strong></p>
    <p>Last name: <strong data-bind="text: hdnlastName">todo</strong></p>
    <p>Full name: <strong data-bind="text: firstHdnLastName"></strong></p> 
    <button data-bind="click: capitalizeHdnLastName">Click Me!!</button>