简体   繁体   English

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

[英]How to pass an object to an module in require.js?

I have these js files: 我有这些js文件:

main.js: main.js:

requirejs(['app']);

app.js: app.js:

define(['messages'], function (messages) {    
    alert(messages.getHello());
});

messages.js: messages.js:

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

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

global.js: global.js:

define(function () {
    var stateObj = {hello:"test!"};

    return {
         getObj: function () { return stateObj; }
    };
});

and index.html as: 和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>

However when I open index.html , I get the below error in console: 但是,当我打开index.html ,在控制台中出现以下错误:

Uncaught ReferenceError: global is not defined  messages.js

where I'm making mistake? 我在哪里犯错?

You just need to set global as an argument to messages.js' function. 您只需要将global设置为messages.js函数的参数即可。 requirejs will pass it in for you. requirejs将为您传递它。

messages.js: messages.js:

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

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

This has the neat side effect that it is impossible to reference a module without declaring it as a dependency. 这样做的副作用是,如果不将模块声明为依赖项,就无法引用该模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM