2017-04-07 22 views
1

這是我的第一篇文章。 我很新的淘汰賽,並嘗試一個基本的例子。 在下面例如:我試圖將標籤更改爲大寫標籤(姓氏和全名)而不是輸入文本框。所以,我最初將文本框的值分配給隱藏字段,並從那裏操作隱藏字段。但是,最後輸入也修改爲大寫。任何幫助深表感謝!!Knockout.js:在未分配的綁定上調用的函數

筆者認爲:

<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());}; 
    } 
+0

你的問題是什麼? –

+0

我想將姓氏(姓名)和姓氏全名更改爲大寫 – Gireesh

回答

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>