简体   繁体   English

RequireJs - 定义与需求

[英]RequireJs - Define vs Require

For modules I don't return an object I have been using require instead of define. 对于模块,我不返回我一直使用的对象而不是define。 For example say I have the following jQuery plugin (jquery.my-plugin.js): 例如,假设我有以下jQuery插件(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();
});

I've found this doesn't work because myPlugin has not been registered. 我发现这不起作用,因为myPlugin尚未注册。 However if I change the require to a define within my jquery.my-plugin module then it works fine. 但是,如果我将require更改为我的jquery.my-plugin模块中的define,那么它可以正常工作。

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 谢谢

Essentially, when you use require you are saying "i want this, but i want all its dependencies too". 基本上,当你使用require你会说“我想要这个,但我也想要它的所有依赖”。 So in the example below, we're requiring A, but require will search for all dependencies and ensure they are loaded before continuing. 因此,在下面的示例中,我们需要A,但require会搜索所有依赖项并确保在继续之前加载它们。

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

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

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. 一般的经验法则是,当您想要定义将由应用程序重用的模块时使用define ,并使用require来简单地加载依赖项。

Below is the code that should be inside jquery.my-plugin.js which defines a module called 'jquery.my-plugin' that can be used as a dependency elsewhere. 下面是应该在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)
        ...
    };
});

Below is a section of code where you want to attach your plugin function to the global jQuery object and then use it ... 下面是一段代码,您希望将插件函数附加到全局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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM