问题描述
对于模块,我不返回我一直使用的对象而不是define。例如,假设我有以下jQuery插件(jquery.my-plugin.js):
For modules I don't return an object I have been using require instead of define. For example say I have the following jQuery plugin (jquery.my-plugin.js):
require(['jquery'], function($) {
$.fn.myPlugin = function(options) {
...
};
});
现在如果我在另一个模块中说出以下内容:
Now if I say the following in another module:
require(['jquery', 'jquery.my-plugin'], function($) {
$('#element').myPlugin();
});
我发现这不起作用,因为myPlugin尚未注册。但是,如果我将需求更改为我的jquery.my-plugin模块中的一个定义,那么它可以正常工作。
I've found this doesn't work because myPlugin has not been registered. However if I change the require to a define within my jquery.my-plugin module then it works fine.
如果有人能清理我的原因,我会很感激去做这个。在继续使用它之前,我想完全理解一些东西。谢谢
I'd appreciate it if someone could clear up why I have to do this. I like to understand something fully before I go ahead and use it. Thanks
推荐答案
基本上,当你使用 require
时,你说我想要这个,但我也想要它所有的依赖。因此,在下面的示例中,我们需要A,但require会搜索所有依赖项并确保在继续之前加载它们。
Essentially, when you use require
you are saying "i want this, but i want all its dependencies too". So in the example below, we're requiring A, but require will search for all dependencies and ensure they are loaded before continuing.
require(['a'], function(a) {
// b, c, d, e will be loaded
});
// File A
define(['b','c','d','e'], function() {
return this;
});
一般的经验法则是你使用 define
如果要定义一个将由应用程序重用的模块,并使用 require
来简单地加载依赖项。
General rule of thumb is you use define
when you want to define a module that will be reused by your application and you use require
to simply load a dependency.
这篇关于RequireJs - 定义与需求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!