2013-10-09 23 views
4

requireJS中的上下文有點麻煩。我想要的是在配置階段(在我加載任何模塊之前)創建一個上下文,「mycontext」,然後將該上下文保存在整個過程中。這很複雜,因爲我不幸需要(< - ha!)爲我的模塊使用CommonJS語法。所以,如果這是我的基本文件看起來是這樣的:requireJS中的上下文和嵌套模塊

base.js

contextReq = require.config({ 
    context: 'mycontext', 
    baseUrl: 'http://www.example.com/src/', 
    paths:{ 
     jquery: 'http://ajax.cdnjs.com/ajax/libs/jquery/2.0.3/jquery.min', 
    }, 
}); 

(function(){ 
    contextReq(['require', 'topModule'], function(require, topModule){ 
     topModule.initialize(); 
    }); 
})(); 

然後,我加載頁首單元:

http://www.example.com/src/topModule.js

define(['require', 'jquery', 'nestedModule'], function (require) { 
    var $ = require('jquery'); 
    var other = require('nestedModule'); 
}); 

威爾的jQuery仍然只能在mycontext中加載?如果我去一個水平進一步:

http://www.example.com/src/nestedModule.js

define(function (require) { 
    var $ = require('jquery'); 
    var oneMore = require('someOtherModule'); 
}); 

我們已經獲得的jQuery在這種情況下,反而會「someOtherModule」也將在此背景下加載,或者在全球「_ 「上下文?有任何方法可以在我進行require調用之前檢查模塊是否已經加載?

謝謝!

回答

7

好的,所以我想出了自己的想法。要求在本地或全球範圍內有一個稱爲「.s」的非常有用的屬性,其中列出了所有需要的上下文。我跑了到控制檯 「require.s.contexts」 我requrie加載完成後:

base.js

contextReq = require.config({ 
    context: 'mycontext', 
    baseUrl: 'http://www.example.com/src/', 
    paths:{ 
     jquery: 'http://ajax.cdnjs.com/ajax/libs/jquery/2.0.3/jquery.min', 
    }, 
}); 

(function(){ 
    contextReq(['require', 'topModule'], function(require, topModule){ 
     topModule.initialize(); 
    }); 
})(); 

//Timeout, then see where we stand 
setTimeout(function() { 
    console.log(require.s.contexts._); 
    console.log(require.s.contexts.mycontext); 
}, 500); 

產量爲如下:

//Console.log for context '_' (the default require context) 
{ 
    [...] 
    defined: [], //empty array, nothing has been loaded in the default context 
    [...] 
} 

//Console.log for context 'mycontext' (the default require context) 
{ 
    [...] 
    defined: [ //Filled out array; everything is loaded in context! 
      topModule: Object 
      nestedModule: Object 
      jquery: function (e,n){return new x.fn.init(e,n,t)} //jQuery function 
    ], 
    [...] 
} 

所以總之,我的預感是正確的:當頂級requireJS模塊被加載到一個特定的上下文中時,即使上下文不再被指定,從該頂級模塊中加載的所有模塊都將加載到上下文中。

+1

請注意,如果您的依賴關係圖中只有一個文件以require([..],function(..){)代替正確的define([..],function(..){)開始,那麼將該文件的所有依賴關係加載到全局('_')上下文中,這會導致奇怪的行爲,並且可能非常痛苦追蹤! – LOAS