Based on the first knockout tutorial, why is my co

2019-06-28 06:31发布

I understand how the tutorial works on the page, but I'm trying to set one up locally to create a calculator and can't get knockout.js to work. It doesn't initialize or populate like the knockout.js online tutorial.

HTML

<html>
<head>
    <script type="text/javascript" language="javascript" src="../knockout-2.1.0.js"></script>
    <script type="text/JavaScript" language="javascript">
        function AppViewModel() {
            this.firstName = ko.observable("Bert");
            this.lastName = ko.observable("Bertington");
        }
        // Activates knockout.js
        ko.applyBindings(new AppViewModel());
    </script> 
</head>
<body class="calc" onLoad="createnav()">

<div id="all">

    <div id="calc">

        <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>
    </div>
    <div id="info">
       <!-- outputs will be here -->
    </div>
</div>
</body>
</html>

I'm using knockout.js version 2.1.0. As for location of the src it is correct.

Folder Structure

  ----------
  | Root   |
  ----------_____________________
     |                             |
   -------------------        ------------       ---------------
  | knockout-2.1.0.js |      |  pphcalc   | ___ | HeroPilot.asp |
   -------------------        ------------       ---------------

Any suggestions?

2条回答
Emotional °昔
2楼-- · 2019-06-28 06:36

You are applying the bindings in a header script tag so there are not yet any elements to bind to at the point that your ko.applyBindings(new AppViewModel()) line runs.

You can provide a callback for the JQuery Window.load function to ensure that everything is properly loaded before the bindings get applied. Example:

<script type="text/JavaScript" language="javascript">
    function AppViewModel() {
        this.firstName = ko.observable("Bert");
        this.lastName = ko.observable("Bertington");
    }

    // Activates knockout.js
    $(window).load(function() {
        ko.applyBindings(new AppViewModel());
    });
</script> 
查看更多
我想做一个坏孩纸
3楼-- · 2019-06-28 06:57

If you're not using jquery, don't load it specially for this. Instead you can activate knockout on window.onload. Example:

Wrap your ko.applyBindings call in a function:

function startKnockout() {
    ko.applyBindings(new AppViewModel());
};

Pass the name of your "start" function to window.onload. Note, don't add the () to the function name. This prevents the function executing immediately, and instead ensures it is called as a callback function when the window is loaded.

window.onload = startKnockout;
查看更多
登录 后发表回答