敲除绑定不起作用,如何解决?

时间:2016-12-18 11:10:58

标签: javascript html knockout.js

我的“index.html”如下。

<!DOCTYPE html>
 <html>
 <head>
 <title>tour </title>
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
 <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js">   </script>
 <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
 <script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>


 </head>
 <body>
 <div class="navbar">
    <div class="navbar-inner">
        <a class="brand" href="#"> tour</a>
    </div>
</div>
<div id="main" class="container">
<!-- layout here -->
    <table class="table table-striped">

        <tr>
            <td>
                <span class="label label-success">Input tour size</span>    
            </td>

            <td>
                <input type="number" data-bind="value: size" id="tour_size" min="3" max="20" >
            </td>
        </tr>
        <tr>
            <td>
                <span class="label label-success">Given locations</span>
            </td>

            <td>
                ​<textarea id="input_list"  data-bind="value: input_value">
                </textarea>
            </td>
        </tr>
        <tr>
            <td>
                <button class="btn" data-bind="click: $root.gen_random_input">Generate</button>
            </td>
            <td>
                <button class="btn" data-bind="click: $root.run_algorithm" >Run</button>
            </td>
        </tr>   
        <tr>
            <td>
                <span class="label label-success" >Best tour</span>
            </td>

            <td>
                ​<textarea id="output_list" data-bind="value: output_value" ></textarea>
            </td>
        </tr>
    </table>




</div>

<script type="text/javascript">

// model
function BestTourModel() 
{
    var self = this;
    self.serverURI = 'http://localhost:8080/api';
    self.size = ko.observable();
    self.input_value = ko.observable();
    self.output_value = ko.observable();

    //methods 

    // generate distinct numbers 
    self.gen_random_input()
    {
        alert("I do random things :)");
    }


    self.run_algorithm();
    {
        alert("I am running now :(");
    }

}

var bestTourModel = new BestTourModel();
ko.applyBindings(bestTourModel, $('#main')[0]);

// some functions

</script>

</body>
</html>

然后我用Chrome打开它,点击这两个按钮,什么都没发生。我寻找其他有相同问题的帖子,但我无法解决我的问题。一切看起来都不错。

1 个答案:

答案 0 :(得分:3)

而不是:

self.gen_random_input()
{
    alert("I do random things :)");
}


self.run_algorithm();
{
    alert("I am running now :(");
}

你必须写下这个:

self.gen_random_input = function()
{
    alert("I do random things :)");
}


self.run_algorithm = function()
{
    alert("I am running now :(");
}