如何将对象传递给require.js中的模块?

时间:2015-05-22 13:09:32

标签: javascript requirejs

我有这些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 as:

<!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

我犯了错误?

1 个答案:

答案 0 :(得分:2)

您只需将global设置为messages.js&#39;的参数。功能。 requirejs会为你传递它。

messages.js:

define(['global'],function (global) {
    var privateFn = global.getObj()

    return {
        getHello: function () {
            if(privateFn.hello == "test!")
                return 'Hello World';
        }
    };
});

这有一个很好的副作用,即如果不将模块声明为依赖项,则无法引用模块。