在外部JavaScript文件中使用KnockoutJS ViewModel

时间:2013-10-24 20:13:23

标签: javascript jquery knockout.js

如何在外部JS文件中创建KO.JS ViewModel,然后在html文件中使用它?这似乎是一件简单的事情,但我无法让它工作,也无法找到有关如何做到这一点的任何明确信息。如果我忽略了,我会道歉,如果有人能指出我的答案,我会删除它。

EXTERNAL vm:

var myApp = (function (myApp) {
myApp.ReportViewModel = function() {
    var self = this;
    self.test = ko.observable();
  }
}(myApp || {}));

单独的HTML文件:

<!DOCTYPE html>
<html>
<head><title>My Page</title></head>
<body>
<table>
    <tr>
        <td>First Name</td>
        <td><input type="text" data-bind='value: test'/></td>
    </tr>
</table>
<h2>Hello, <span data-bind="text: test"> </span>!</h2>

<!-- reference this *before* initializing -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">       </script>
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
<script src="myApp.js"></script>

<!-- fire off your app -->
<script>
    ($function(){
       var reportVM = new myApp.ReportViewModel();
       ko.applyBindings(reportVM);
    });
</script>

修改 的 我做了建议的更改。这是我的项目现在看起来像但它仍然无法正常工作。此外,knockout.js代码根本没有运行。

1 个答案:

答案 0 :(得分:4)

你走在正确的道路上。作为@nemesv注释,您可能需要在使用它之前引用外部JS。另外,我建议为您的应用程序创建一个名称空间对象。所有这些一起看起来像这样:

<html>
<head><title>My Page</title></head>
<body>
    <table>
        <tr>
            <td>First Name</td>
            <td><input type="text" data-bind='value: test'/></td>
        </tr>
    </table>
    <h2>Hello, <span data-bind="text: test"> </span>!</h2>

    <!-- reference this first -->
    <script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

    <!-- reference this *before* initializing -->
    <script src="myApp.js"></script>

    <!-- fire off your app -->
    <script>
        $(function(){
           var reportVM = new myApp.ReportViewModel();
           ko.applyBindings(reportVM);
        });
    </script>
</body>
</html>

PS。请注意,我在第二行中将new reportVM更改为reportVM。这只是一个变量,不需要“新”它。另外,我已修复了该位脚本上的括号位置。

myApp.js中有这个:

var myApp = (function (myApp) {
    myApp.ReportViewModel = function() {
        var self = this;
        self.test = ko.observable("Testing 123");
    }

    return myApp;
}(myApp || {}));

这样,应用程序的ReportViewModel和其他构造函数之类的东西不会在全局命名空间中停留,但会成为myApp对象的一部分(“命名空间”,如果你愿意的话)。