如何将对象传递给 require.js 中的模块?
How to pass an object to an module in require.js?
我有这些 js 文件:
main.js:
requirejs(['app']);
app.js:
define(['messages'], function (messages) {
alert(messages.getHello());
});
messages.js:
define(['global'],function () {
var privateFn = global.getObj()
return {
getHello: function () {
if(privateFn.hello == "test!")
return 'Hello World';
}
};
});
global.js:
define(function () {
var stateObj = {hello:"test!"};
return {
getObj: function () { return stateObj; }
};
});
和index.html为:
<!DOCTYPE html>
<html>
<head>
<!-- Include the RequireJS library. We supply the "data-main" attribute to let
RequireJS know which file it should load. This file (scripts/main.js) can
be seen as the entry point (main) of the application. -->
<script data-main="scripts/main" src="lib/require.js"></script>
</head>
<body>
<h1>Example 2: load module using explicit dependency syntax</h1>
</body>
</html>
然而,当我打开 index.html
时,我在控制台中收到以下错误:
Uncaught ReferenceError: global is not defined messages.js
我哪里弄错了?
您只需将 global
设置为 messages.js' 函数的参数。 requirejs 会为你传递它。
messages.js:
define(['global'],function (global) {
var privateFn = global.getObj()
return {
getHello: function () {
if(privateFn.hello == "test!")
return 'Hello World';
}
};
});
这有一个很好的副作用,即如果不将模块声明为依赖项就无法引用它。
我有这些 js 文件:
main.js:
requirejs(['app']);
app.js:
define(['messages'], function (messages) {
alert(messages.getHello());
});
messages.js:
define(['global'],function () {
var privateFn = global.getObj()
return {
getHello: function () {
if(privateFn.hello == "test!")
return 'Hello World';
}
};
});
global.js:
define(function () {
var stateObj = {hello:"test!"};
return {
getObj: function () { return stateObj; }
};
});
和index.html为:
<!DOCTYPE html>
<html>
<head>
<!-- Include the RequireJS library. We supply the "data-main" attribute to let
RequireJS know which file it should load. This file (scripts/main.js) can
be seen as the entry point (main) of the application. -->
<script data-main="scripts/main" src="lib/require.js"></script>
</head>
<body>
<h1>Example 2: load module using explicit dependency syntax</h1>
</body>
</html>
然而,当我打开 index.html
时,我在控制台中收到以下错误:
Uncaught ReferenceError: global is not defined messages.js
我哪里弄错了?
您只需将 global
设置为 messages.js' 函数的参数。 requirejs 会为你传递它。
messages.js:
define(['global'],function (global) {
var privateFn = global.getObj()
return {
getHello: function () {
if(privateFn.hello == "test!")
return 'Hello World';
}
};
});
这有一个很好的副作用,即如果不将模块声明为依赖项就无法引用它。