2014-02-09 166 views
1

我可能會問這是在這個環節上給予約Knockoutjs問題聽起來很傻: http://jsfiddle.net/VR5aa/ 的代碼給出如下:Claryfying約淘汰賽JS

HTML

<!-- This is a *view* - HTML markup that defines the appearance of your UI --> 

<p>First name: <strong data-bind="text: firstName"></strong></p> 
<p>Last name: <strong data-bind="text: lastName"></strong></p> 

<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> 

和JS :

// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI 
function AppViewModel() { 
    this.firstName = ko.observable("Bert"); 
    this.lastName = ko.observable("Bertington"); 

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

// Activates knockout.js 
ko.applyBindings(new AppViewModel()); 

什麼讓我在淘汰賽中困惑是使用括號。例如在文本綁定中,我們可以使用text:firstName(),但它也可以使用。 我也嘗試以下操作:

console.log(typeof this.firstName); //returns function 
console.log(typeof this.firstName()); //returns string 

所以請有人可以詳細()在淘汰賽JS的使用。由於

回答

0

如果綁定到可觀察到的,其中的firstName是,那麼你可能要麼

text:firstName() 

OR

text:firstName 

和淘汰賽將是足夠聰明,做正確的事。現在,如果的firstName是一個函數,像

firstName: function(){ 
    return "Bert"; 
} 

那麼你就必須用括號

text:firstName() 

手動調用該函數在bidning如果你只是做

text:firstName 

使用普通的JavaScript函數,那麼函數的字符串表示就會顯示在您的UI中,這將成爲現代瀏覽器中函數本身的文本。

這是行動中的live demo

+0

感謝亞當開始簡單的視頻,您可以檢查該播放列表。我清楚地知道我的困惑。 – Pant