Knockoutjs程序无效

时间:2012-10-22 08:30:12

标签: mvvm knockout.js

我是Knockoutjs的新手,从http://learn.knockoutjs.com/ tutorial开始,但是当我在当地尝试时,它是无效的。

我是否需要在单独的文件或相同的文件中编写模型和视图,我的问题是如何运行第一个淘汰赛程序。

<!DOCTYPE HTML>
<html>
    <head>
    <title></title>
        <script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js'></script>
        <script type="text/javascript">
                    // Here's my data model
            var ViewModel = function(first, last) {
                this.firstName = ko.observable(first);
                this.lastName = ko.observable(last);
                this.fullName = ko.computed(function() {
                    // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
                    return this.firstName() + " " + this.lastName();
                }, this);
            };

            ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work​​​​​​​​​​​​​​​​​​
            </script>
    </head>
    <body>
            <div class='liveExample'>   
    <p>First name: <input data-bind='value: firstName' /></p> 
    <p>Last name: <input data-bind='value: lastName' /></p> 
    <h2>Hello, <span data-bind='text: fullName'> </span></h2>  
</div>​
    </body>
</html>

1 个答案:

答案 0 :(得分:3)

您应该将ko.applyBindings放到页面末尾。以下是官方文档的引用:

  

要激活Knockout,请将以下行添加到块中:

     

ko.applyBindings(myViewModel);

     

您可以将脚本块放在HTML的底部   文档,或者您可以将它放在顶部并将内容包装在一个   支持DOM的处理程序,例如jQuery的$ function。

因此代码应如下所示:

<!DOCTYPE HTML>
<html>
    <head>
    <title></title>
        <script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js'></script>
    </head>
    <body>
       <div class='liveExample'>   
           <p>First name: <input data-bind='value: firstName' /></p> 
           <p>Last name: <input data-bind='value: lastName' /></p> 
           <h2>Hello, <span data-bind='text: fullName'> </span></h2>  
       </div>​
       <script type="text/javascript">
            // Here's my data model
            var ViewModel = function(first, last) {
                this.firstName = ko.observable(first);
                this.lastName = ko.observable(last);
                this.fullName = ko.computed(function() {
                    // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
                    return this.firstName() + " " + this.lastName();
                }, this);
            };

            ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work​​​​​​​​​​​​​​​​​​
       </script>
    </body>
</html>

这是工作小提琴:http://jsfiddle.net/vyshniakov/s2LSE/