2014-02-09 167 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