簡體   English   中英

RequireJs - 定義與需求

[英]RequireJs - Define vs Require

對於模塊,我不返回我一直使用的對象而不是define。 例如,假設我有以下jQuery插件(jquery.my-plugin.js):

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

現在如果我在另一個模塊中說出以下內容:

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

我發現這不起作用,因為myPlugin尚未注冊。 但是,如果我將require更改為我的jquery.my-plugin模塊中的define,那么它可以正常工作。

如果有人能清楚我為什么要這樣做,我會很感激。 在繼續使用它之前,我想完全理解一些東西。 謝謝

基本上,當你使用require你會說“我想要這個,但我也想要它的所有依賴”。 因此,在下面的示例中,我們需要A,但require會搜索所有依賴項並確保在繼續之前加載它們。

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
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM