2016-09-18 144 views
1

我的網頁有不同的js組件來處理不同的業務邏輯。我正在使用RequireJS來管理依賴關係。我想動態加載所需的組件。Requirejs在define()中加載不同的js文件

例如:

define(['something'],function(something){ 
    var processor; 
    if(userRole === "student"){ 
     //I want to dynamically load studentProcessor.js here; 
    } 
    else if(userRole === "teacher"){ 
     //I want to dynamically load teacherProcessor.js here; 
    }  

    processor.process(); 
}); 

很感激,如果任何人都可以告訴我什麼是處理的最佳方式。

回答

2

我認爲處理這種問題最簡潔的方法是從用戶角色到處理器的映射。 然後在您的功能中,您仍然需要檢查userRole是否已設置,並且已定義該角色的處理器。

// This is where processors are associated to user roles. 
var roleToProcessorMapping = 
{ 
    student: './studentProcessor.js', 
    teacher: './teacherProcessor.js' 
}; 

define(['something'],function(something){ 
    if(userRole){ 
     var processorPath = roleToProcessorMapping[userRole]; 
     if(processorPath){ 
     require([processorPath], function(processor){ 
      processor.process(); 
     }); 
     return; 
     } 
    } 
    // handle error 
}); 
+1

謝謝你的幫助〜但是我從requirejs得到了一個「Module name」***「還沒有加載上下文」的錯誤。所以我必須修改'''processor = require(path)''''require'(require)([path],function(processor){})''以修復它。這是否正確? –

+0

當然@RyanHu,我正在考慮Node.js語法,但是,是的,這就是您用requirejs加載模塊的方式。 –