3

我有一个主干项目,我正在使用 require.js 来模块化代码。

我的 main.js 看起来像这样:

require.config({
    paths:{
        jquery:'../../../../core/js/external/jquery/jquery-1.8.2',
        underscore:'../../../../core/js/external/underscore/underscore',
        backbone:'../../../../core/js/external/backbone/backbone',
        text:'../../../../core/js/external/require/text',
        backbone_paginate:'../../../../core/js/external/backbone/backbone.pagination',
        'jquery.sprites':'../../../../core/js/sprites',
        'jquery.sprite_util':'../../../../core/js/util/spriteUtil'


    },
    shim:{
        'backbone':{
            deps:['underscore', 'jquery'],
            exports:'Backbone'
        },
        'underscore':{
            exports:'_'
        },
        'jquery.blades':{
            deps:['jquery']
        },

        'jquery.sprites':{
            deps:['jquery']
        },
        'jquery.sprite_util':{
            deps:['jquery.sprites']
        }
    }
    }
});
require(['../app'], function (AppView) {
    "use strict";
    new AppView();
});

所以,这里的 jquery.sprites 和 jquery.utils 是我需要使用的插件,而不会将它们包含在我的视图中。目前,我必须将它们包括在任何使用它们的地方。例如:

define([
  'jquery',
  'underscore',
  'backbone',
  'views/SimpleNamedObjectView',
  'jquery.sprites',
  'jquery.sprite_util',


], function($, _, Backbone, SimpleNamedObjectView){
  "use strict";

有没有一种方法可以访问 jquery.sprites 和 jquery.sprite_util 而无需在每个视图中都包含它们?它是否可以对 main.js 中的所有视图变得全局,以便我可以使用这些插件的功能而不将它们包含在所有视图中?例如 this.$el.getSprites(); (其中 getSprites 是 jquery.sprites 的一个方法)

4

1 回答 1

3

Once they're loaded, as they're "shimmed", they're going to be available globally.

So you could call them as dependencies in your bootstrapping require call inside main.js. This would work.

But! That's completely against the philosophy of Require.js and AMD. Each module should declare all their dependencies so they can all be loaded individually and work as is. This would also allow for easier unit testing.

So, yes you can, but you really shouldn't do this.

于 2012-12-21T02:15:46.087 回答