无法获得最简单的knockout.js样本吗? [英] Can't get the most simple knockout.js sample to work?

查看:97
本文介绍了无法获得最简单的knockout.js样本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真让我烦恼。请查看knockout.js的 Hello World示例

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

这是我的代码:

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

似乎绑定不起作用。如果我 alert(viewModel.fullName()); 我按预期获得Planet Earth。但输入元素和跨度都没有填充数据。

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.

我做错了什么?

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

Here is a zip file which includes both my file and knockout.js

推荐答案

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

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

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

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

这篇关于无法获得最简单的knockout.js样本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆