gpt4 book ai didi

javascript - 在外部 JavaScript 文件中使用 KnockoutJS ViewModel

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:47:33 24 4
gpt4 key购买 nike

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

外部虚拟机:

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 代码根本没有运行。

最佳答案

您走在正确的道路上。正如@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>

附言。请注意,我在第二行将 new reportVM 更改为 reportVM。那时它只是一个 var,不需要“新建”它。此外,我还修复了那段脚本上的括号位置。

myApp.js 中有这个:

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

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

这样,ReportViewModel 和您的应用程序的其他构造函数就不会留在全局命名空间中,而是成为 myApp 对象(“命名空间” ,如果你愿意的话)。

关于javascript - 在外部 JavaScript 文件中使用 KnockoutJS ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19575729/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com