我正在浏览下面从 http://backbonejs.org/backbone.js 复制的 Backbone.js 源代码
(function(root, factory) {
// Set up Backbone appropriately for the environment. Start with AMD.
if (typeof define === 'function' && define.amd) {
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
// Export global even in AMD case in case this script is loaded with
// others that may still expect a global Backbone.
root.Backbone = factory(root, exports, _, $);
});
// Next for Node.js or CommonJS. jQuery may not be needed as a module.
} else if (typeof exports !== 'undefined') {
var _ = require('underscore');
factory(root, exports, _);
// Finally, as a browser global.
} else {
root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
}
}(this, function(root, Backbone, _, $) {
// Initial Setup
// -------------
// Save the previous value of the `Backbone` variable, so that it can be
// restored later on, if `noConflict` is used.
var previousBackbone = root.Backbone;
// Create local references to array methods we'll want to use later.
var array = [];
var push = array.push;
var slice = array.slice;
var splice = array.splice;
// Current version of the library. Keep in sync with `package.json`.
Backbone.VERSION = '1.1.2';
// For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
// the `$` variable.
Backbone.$ = $;
在 CommonJS/node.js 配置中,它说 Next for Node.js 或 CommonJS。 jQuery 可能不需要作为一个模块。
并调用 factory(root, exports, _)
并使用未定义的 jquery 的第四个 $
参数。在工厂函数中它是 Backbone.$ = $
所以 Backbone.$
是未定义的?那么很多东西(AJAX、$el
包装等)不会中断吗?
最佳答案
使用 jQuery 的主要原因是为了处理 DOM 操作,而这在后端 (nodejs) 中是无用的,因此无需将其作为依赖项加载。要解决这个问题,您可以创建一个简单的模块,用 jQuery 返回 BackboneJS。
// libs/backbone.js
var backbone = require("backbone");
backbone.$ = require("jquery");
module.exports = backbone;
关于javascript - 如何在 CommonJS 模块配置中设置 Backbone.$?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25924595/