澄清Knockout JS

时间:2014-02-09 04:56:22

标签: javascript knockout.js

通过在这个链接中提出关于Knockoutjs的问题,我可能听起来很傻: http://jsfiddle.net/VR5aa/ 代码如下:

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());

Knockout让我感到困惑的是使用Brackets。例如,在文本绑定中,我们可以使用 text:firstName(),但这也适用。  我也尝试过:

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

所以请有人详细说明Knockout JS中()的用法。感谢

2 个答案:

答案 0 :(得分:0)

如果你绑定了一个名为firstName的observable,那么你可以

text:firstName()

OR

text:firstName

和淘汰赛将足够聪明,做正确的事情。现在,如果firstName是一个函数,比如

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

然后你必须用括号

手动调用出价中的函数
text:firstName()

如果你只是做

text:firstName

使用普通的JavaScript函数,然后函数的字符串表示将显示在UI中,这将是现代浏览器中函数本身的文本。

以下是live demo的实际操作。

答案 1 :(得分:0)

您可以查看此播放列表,因为它包含有关淘汰赛的简单视频

https://www.youtube.com/playlist?list=PLCyiZP-cRGcAozahbiVrFQ2FvIUDLG9XU

从基本

开始