javascript requirejs 定义未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33279743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
requirejs define is not defined
提问by Boy Pasmo
I'm trying to implement knockoutjs and requirejs to my asp.net mvc app.
我正在尝试在我的 asp.net mvc 应用程序中实现 Knockoutjs 和 requirejs。
So, here's what I have.
所以,这就是我所拥有的。
Views/Shared/_Layout.cshtml
视图/共享/_Layout.cshtml
<html>
<body>
@RenderBody()
<script src="~/Scripts/require.js" data-main="/Scripts/app/main"></script>
@RenderSection("scripts", required: false)
</body>
<html>
Scripts/main.js
脚本/main.js
require.config({
baseUrl: '/Scripts',
paths: {
ko: '/Scripts/knockout-3.3.0'
}
});
Views/Product/Index.cshtml(one of my views)
Views/Product/Index.cshtml(我的观点之一)
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="foreach: products">
<tr>
<td data-bind="text: $data.product"></td>
</tr>
</tbody>
</table>
<script src="~/Scripts/app/product.js"></script>
@section scripts {
// Some scripts here
}
Scripts/app/product.js
脚本/应用程序/product.js
define(['ko'], function (ko) {
var data = [
{ name: 'Product1' },
{ name: 'Product2' }
];
var Product = function () {
this.name = ko.observable()
};
var productVm = {
products: ko.observableArray([]),
load: function() {
for (var i = 0; i < data.length; i++) {
productVm.products.push(new Product()
.name(data[i].name));
}
}
}
productVm.load();
ko.applyBindings(productVm);
});
Just in case you need to see my folder structure
以防万一您需要查看我的文件夹结构
Solution
- Scripts
-- app
--- product.js
-- require.js
-- knockout-3.3.0.js
- Views
-- Product
--- Index.cshtml
-- Shared
--- _Layout.cshtml
Then, once I navigate to my products index page. I got a define is not define
error. What am I missing?
然后,一旦我导航到我的产品索引页面。我有一个define is not define
错误。我错过了什么?
回答by Dandy
Include following in your main.js
将以下内容包含在您的 main.js
require(["app/product"], function () {
});
And modify index.html
as follows
并修改index.html
如下
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="foreach: products">
<tr>
<td data-bind="text: $data.name"></td>
</tr>
</tbody>
</table>
@section scripts {
}
If you intend to use RequireJS for multi page application, then also read this.
如果您打算将 RequireJS 用于多页面应用程序,那么也请阅读此。