RequireJs – 定义vs要求

对于模块,我不返回一个我一直使用的对象而不是定义。 例如说我有以下jQuery插件(jquery.my-plugin.js):

require(['jquery'], function($) { $.fn.myPlugin = function(options) { ... }; }); 

现在,如果我在另一个模块中说下面的话:

 require(['jquery', 'jquery.my-plugin'], function($) { $('#element').myPlugin(); }); 

我发现这是行不通的,因为myPlugin尚未注册。 但是,如果我更改需求到我的jquery.my插件模块中的定义,那么它工作正常。

如果有人能澄清为什么我必须这样做,我会很感激。 在我继续使用之前,我想充分理解一些东西。 谢谢

从本质上讲,当你使用require你会说“我想要这个,但我也想要所有的依赖”。 所以在下面的例子中,我们要求A,但是require会search所有的依赖关系,并确保它们在继续之前被加载。

 require(['a'], function(a) { // b, c, d, e will be loaded }); // File A define(['b','c','d','e'], function() { return this; }); 

一般的经验法则是,当你想定义一个将被你的应用程序重用的模块时,你使用了define ,并且你使用require来简单地加载一个依赖。

下面是应该在jquery.my-plugin.js里面的代码,它定义了一个名为“jquery.my-plugin”的模块,可以在其他地方用作依赖项。

 define(['jquery'], function($) { //jquery is a dependency to the jquery.my-plugin module $.fn.myPlugin = function(options) { //adds a function to the *global* jQuery object, $ (global since jQuery does not follow AMD) ... }; }); 

下面是一段代码,你想把你的插件函数附加到全局jQuery对象,然后使用它…

 require(['jquery.my-plugin'], function() { // jquery.my-plugin is loaded which attaches the plugin to the global JQuery object as shown above, then this function fires //the only reason $ is visible here is because it's global. If it was a module, you would need to include it as a dependency in the above require statement $('#element').myPlugin(); //the $ refers to the global object that has the plugin attached });