javascript 无法使用最简单的 Knockout.js 示例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7154703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:07:19  来源:igfitidea点击:

Can't get the most simple knockout.js sample to work?

javascripthtmlknockout.js

提问by Sandro

This really bothers me. Please have a look at the Hello World exampleof knockout.js.

这真的让我很困扰。请看一下knockout.js的Hello World 示例

Here is my code:

这是我的代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Home Page</title>
    <script src="knockout-1.2.1.debug.js" type="text/javascript"></script>

    <script type="text/javascript">
        // Here's my data model
        var viewModel = {
            firstName: ko.observable("Planet"),
            lastName: ko.observable("Earth")
        };
        viewModel.fullName = ko.dependentObservable(function () {
            // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
            return viewModel.firstName() + " " + viewModel.lastName();
        });

        ko.applyBindings(viewModel); // This makes Knockout get to work
    </script>

</head>
<body>
    <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>
</body>
</html>

It seems, that the binding doesn't work. If I alert(viewModel.fullName());I get "Planet Earth" as expected. But neither the input elements nor the span gets filled with data.

看来,绑定不起作用。如果我alert(viewModel.fullName());按预期得到“行星地球”。但是输入元素和跨度都没有填充数据。

What am I doing wrong?

我究竟做错了什么?

Hereis a zip file which includes both my file and knockout.js

是一个 zip 文件,其中包含我的文件和 Knockout.js

回答by RP Niemeyer

Your issue is that you are calling ko.applyBindings too soon.

您的问题是您过早地调用了 ko.applyBindings。

You want to either move your script tag to the bottom or execute it in an onload or something like jQuery's ready function.

您想将脚本标签移到底部,或者在 onload 或类似 jQuery 的就绪函数中执行它。

回答by Bijoy Meethal

Just add window.onload= function() in the beginning of script..

只需在脚本的开头添加 window.onload= function() ..

  window.onload= function() {

    // Here's my data model
    var viewModel = {
......
    ko.applyBindings(viewModel); // This makes Knockout get to work
  }
</script>

回答by moshe beeri

This is a working version of the KnockoutJs tutorial.

这是 KnockoutJs 教程的工作版本。

 <!DOCTYPE html>
<html>
<head>

    <link rel="stylesheet" type="text/css" href="style/monitor.css">
    <script type="text/javascript" src="js/knockout-2.3.0.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
        function WebmailViewModel() {
            // Data
            var self = this;
            self.folders = [ 'Inbox', 'Archive', 'Sent', 'Spam' ];
            self.chosenFolderId = ko.observable();
            self.chosenFolderData = ko.observable();
            self.chosenMailData = ko.observable();

            // Behaviours    
            self.goToFolder = function(folder) {
                self.chosenFolderId(folder);
                self.chosenMailData(null); // Stop showing a mail
                $.get('/mail', {
                    folder : folder
                }, self.chosenFolderData);
            };
            self.goToMail = function(mail) {
                self.chosenFolderId(mail.folder);
                self.chosenFolderData(null); // Stop showing a folder
                $.get("/mail", {
                    mailId : mail.id
                }, self.chosenMailData);
            };

            // Show inbox by default
            self.goToFolder('Archive');
        };


    </script>
</head>
<body onload="ko.applyBindings(new WebmailViewModel());">
    <!-- Folders -->
    <ul data-bind="foreach: folders">
        <li>
            The current folders are: <b data-bind="text: $data"></b>
        </li>
    </ul>   
    </body>
    </html>

回答by Ajay

The ko.applyBindings()should called once the view gets loaded then the data gets binded to the controls automatically.

ko.applyBindings()一旦视图获取自动加载,然后得到的数据绑定到控件应该叫。

回答by gislikonrad

Looking at the demos for knockout.js, you're missing one thing. You're not sending the view model as a parameter in to the dependentObservable function:

查看knockout.js 的演示,您错过了一件事。您没有将视图模型作为参数发送到dependentObservable 函数中:

viewModel.fullName = ko.dependentObservable(function () {
        // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
        return viewModel.firstName() + " " + viewModel.lastName();
    }, viewModel);

回答by Bajju

If the values are not binding just fire up a check functionality before you make use of the array. In knockout you can do this like

如果这些值没有绑定,只需在使用数组之前启动检查功能。在淘汰赛中,您可以这样做

< !-- ko if:detail() -->


   --your HTML code to display the fields goes here--


 <!-- /ko -->