使用RequireJS加载主干和下划线

我正在尝试使用RequireJS加载Backbone和Underscore(以及jQuery)。使用最新版本的Backbone和Underscore,似乎有些棘手。例如,Underscore自动将自身注册为模块,但Backbone假定Underscore在全球范围内可用。我还应该注意,Backbone似乎并没有将自身注册为模块,这使其与其他库不一致。这是我能想到的最好的main.js:


require(

{

    paths: {

        'backbone': 'libs/backbone/backbone-require',

        'templates': '../templates'

    }

},

[

    // jQuery registers itself as a module.

    'http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js',


    // Underscore registers itself as a module.

    'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.1/underscore-min.js'

], function() {


    // These nested require() calls are just due to how Backbone is built.  Underscore basically says if require()

    // is available then it will automatically register an "underscore" module, but it won't register underscore

    // as a global "_".  However, Backbone expects Underscore to be a global variable.  To make this work, we require

    // the Underscore module after it's been defined from within Underscore and set it as a global variable for

    // Backbone's sake.  Hopefully Backbone will soon be able to use the Underscore module directly instead of

    // assuming it's global.

    require(['underscore'], function(_) {

        window._ = _;

    });


    require([

        'order!http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js',

        'order!app'

    ], function(a, app) {

        app.initialize();

    })

});

慕村9548890
浏览 380回答 3
3回答

慕尼黑的夜晚无繁华

现在,RequireJS 2.X使用新shim配置可以更好地有机解决非AMD模块,例如Backbone&Underscore 。该shim配置易于使用:(1)声明依赖项(deps)(如果有)(可能来自paths配置,也可能是有效路径本身)。(2)(可选)从要填充的文件中指定全局变量名称,该名称应导出到需要它的模块函数中。(如果不指定导出,则只需要使用全局变量,因为没有东西会传递到您的require / define函数中。)这是shim加载Backbone 的简单示例用法。即使没有任何依赖性,它也会为下划线添加导出。require.config({  shim: {    underscore: {      exports: '_'    },    backbone: {      deps: ["underscore", "jquery"],      exports: "Backbone"    }  }});//the "main" function to bootstrap your coderequire(['jquery', 'underscore', 'backbone'], function ($, _, Backbone) {   // or, you could use these deps in a separate module using define});注意:此简化的代码假定jquery,bone和underscore位于与此“ main”代码相同的目录下的名为“ jquery.js”,“ backbone.js”和“ underscore.js”的文件中(这成为require的baseURL )。如果不是这种情况,则需要使用path config。我个人认为,使用内置shim功能,不使用分叉版本的Backbone&Underscore的优势要胜过使用另一个流行答案中推荐的AMD叉的优势,但是无论哪种方式都可以。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript