4

我想摆脱全局 jQuery 对象(window.$ 可能还有 window.jQuery)。

数据主要:

require.config({
    paths: {
        "jquery": "jquery-2.0.0"
    },
    shim: {
        "bootstrap": {
            deps: ["jquery"]
        },
        "jquery": {
            deps: [],
            init: function() {
                return this.jQuery.noConflict(true);
            },
            exports: "jQuery"
        }
    }
});

require(["jquery", "bootstrap"], function($) {
    // ...
});

这段代码有什么问题?“init”永远不会被调用。

4

2 回答 2

4

它很可能不会被调用,因为它jQuery实现了 AMD 模块并且不需要 shim。

于 2013-05-24T20:55:09.843 回答
4

RequireJS 网站上最近更新的Use with jQuery页面解释了为什么会发生这种情况以及您可以采取哪些措施来解决它。以下是相关部分:

jQuery 将自己注册为全局变量“$”和“jQuery”,即使它检测到 AMD/RequireJS。AMD 方法建议不要使用全局函数,但关闭这些 jQuery 全局函数的决定取决于您是否有依赖于它们的非 AMD 代码。jQuery 有一个 noConflict 函数,它支持释放对全局变量的控制,这可以在你的 require.config 中自动执行,我们稍后会看到。

如果你想抑制这些全局函数,你需要使用一个map配置到一个 noConflict 包装模块而不是一个shim配置。正如@tomaskirda 指出的那样,jQuery 不会触发shim.init支持 AMD 的库。Use with jQuery页面中的相关代码:

require.config({
    // Add this map config in addition to any baseUrl or
    // paths config you may already have in the project.
    map: {
      // '*' means all modules will get 'jquery-private'
      // for their 'jquery' dependency.
      '*': { 'jquery': 'jquery-private' },

      // 'jquery-private' wants the real jQuery module
      // though. If this line was not here, there would
      // be an unresolvable cyclic dependency.
      'jquery-private': { 'jquery': 'jquery' }
    }
});

// and the 'jquery-private' module, in the
// jquery-private.js file:
define(['jquery'], function (jq) {
    return jq.noConflict( true );
});
于 2013-06-28T13:23:55.780 回答