[英]Backbone AMD with requireJs
From the Logs, Backbone now registers itself for AMD (Require.js) Since v1.1.1. 从Logs开始,Backbone现在为AMD(Require.js)自v1.1.1注册。
Great, So I try to do the same for a module but there is something I don't understand. 太棒了,所以我尝试对模块做同样的事情,但有一些我不明白的事情。
If we look at section 4 of annotated sources the sources, The module doesn't return the global Backbone. 如果我们看一下注释源的第4节来源,该模块不会返回全局Backbone。
No need shim and window.Backbone is available. 不需要垫片和窗口.Backbone可用。 But How Backbone can not be undefined ?
但是Backbone如何不能被定义?
// Definition Backbone Module //定义Backbone模块
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
root.Backbone = factory(root, exports, _, $);
});
// Require Backbone module //需要Backbone模块
require(['backbone'], function (Backbone) {
Backbone // is not undefined ?
});
// Modal module Definition //模态模块定义
define(['jquery'], function ($) {
root.Modal = factory(root, {}, $);
});
// Require Modal module //需要模态模块
require(['modal'], function (Modal) {
Modal // undefined
});
Into my module (using the same structure), When I require my module, I got undefined
if I don't return anything. 进入我的模块(使用相同的结构),当我需要我的模块时,如果我不返回任何内容,我会得到
undefined
。
I have to return root.Modal in order to make it work. 我必须返回root.Modal以使其工作。
return root.Modal = factory(root, {}, $);
The main question is " How a module can be required while the module doesn't return anything ? " 主要问题是“ 模块不返回任何内容时如何需要模块? ”
I have missing something on requireJS, but I don't find it. 我在requireJS上遗漏了一些东西,但我找不到它。
http://backbonejs.org/docs/backbone.html#section-4 http://backbonejs.org/docs/backbone.html#section-4
The code in question is this: 有问题的代码是这样的:
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
root.Backbone = factory(root, exports, _, $);
});
Note now factory
is called with exports
as the 2nd parameter. 注意现在使用
exports
作为第二个参数调用factory
。 The factory function is going to export Backbone's methods by setting fields on this object. 工厂函数将通过设置此对象上的字段来导出Backbone的方法。 This is why when you require Backbone, you get a useful value and not
undefined
or garbage. 这就是为什么当你需要Backbone时,你得到一个有用的值而不是
undefined
或垃圾。
This reason this works is that RequireJS supports defining a module by returning a value from the factory function you give to define
, so you can do this: 这样做的原因是RequireJS支持通过从您给
define
的工厂函数返回一个值来define
,因此您可以这样做:
define(function () {
return {
foo: function () { ... }
};
});
But it supports also other means to do this, like for instance: 但它也支持其他方法,例如:
define(['exports'], function (exports) {
exports.foo = function () { ... };
});
In the code above the module named exports
in the list of dependencies is a special (and reserved) module name which means "give me an object on which I can set fields to export values". 在上面的代码中,依赖项列表中名为
exports
的模块是一个特殊的(和保留的)模块名称,这意味着“给我一个对象,我可以在其上设置字段以导出值”。 Backbone uses this 2nd way of exporting a value. Backbone使用第二种方式导出值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.