使用require.js后,如何通过简单的脚本引用访问jquery全局命名空间?

时间:2012-08-04 01:56:55

标签: javascript jquery

我想编写一个在每个apge上运行的脚本 - 它使用我刚加载的jquery插件 - 并在加载所有插件后首先运行它。根据迄今为止的评论,这需要在Require.js中定义和运行模块......

我在包含我的Require.js代码的CMS中有页脚部分,因此:

<!-- special version of jQuery with RequireJS built-in -->
script data-main="/addons/shared_addons/themes/base/js/main" src="/addons/shared_addons/themesbase/js/require-jquery.js" type="text/javascript"> /script

...而且我的main.js非常标准:

// urlArgs: "bust=v1"  // for release
require.config({
    urlArgs: "bust=" + (new Date()).getTime(),
    paths: {
        Corner: "/addons/shared_addons/themes/base/js/jquery.corner",
        JQForm: "/addons/shared_addons/themes/base/js/jquery.form",
        Gritter: "/addons/shared_addons/themes/base/js/jquery.gritter.min",
        JQUI: "/addons/shared_addons/themes/base/js/jquery-ui-1.8.21.custom.min",
        TimePicker: "/addons/shared_addons/themes/base/js/jquery.ui.timepicker",
        DateFormat: "/addons/shared_addons/themes/base/js/date.format",
        countdown: "/addons/shared_addons/themes/base/js/jquery.countdown.min",
        JQMustache: "/addons/shared_addons/themes/base/js/jquery-Mustache",
        Mustache: "/addons/shared_addons/themes/base/js/mustache",
        Kendo: "/addons/shared_addons/themes/base/js/kendo.web.min",
        Chosen: "/addons/shared_addons/themes/base/js/chosen.jquery.min",
        EveryPage: "/addons/shared_addons/themes/base/js/another_doc_ready_script"
    }       
});

require([
'jquery', 
'Corner',
'JQForm',
'Gritter',
'JQUI',
'TimePicker',
'DateFormat',
'countdown',
'JQMustache',
'Mustache',
'Kendo',
'Chosen'
],
[ "EveryPage" ],
function($) {
    //run
    $(function() {
        console.log('get everything we could possibly need');
    });
});

“another_doc_ready_script.js”包含“everypage”模块定义:

console.log('here');
define("EveryPage",
        [
        'jquery', 
        'Corner',
        'JQForm',
        'Gritter',
        'JQUI',
        'TimePicker',
        'DateFormat',
        'countdown',
        'JQMustache',
        'Mustache',
        'Kendo',
        'Chosen'
        ],
    function($) {
console.log('in everypage');
$(document).ready(function() { 
    console.log('in everypage doc ready');
        $( "body").removeClass('nodisplay');
    }); // document ready
console.log('leaving everypage');
   }  // function-define-require
); // define-require

编辑:Bergi的评论this更有意义。我已经调整了上面的代码,但它仍然无效。压缩。纳达。没有控制台日志语句或错误。这必须是一种常见用法,但我找不到一个简单的例子。

1 个答案:

答案 0 :(得分:1)

来自the docs

  

模块不同于传统的脚本文件[...]。它可以明确列出其依赖项[...]。

     

[That]允许尽可能快地加载它们,甚至乱序,但是以正确的依赖顺序进行评估。

section § 1.2.3中描述了如何定义具有依赖关系的模块。