Requirejs 在 define() 中加载不同的 js 文件
Requirejs load different js file inside define()
我的网页有不同的 js 组件来处理不同的业务逻辑。我正在使用 RequireJS 来管理依赖项。我想动态加载所需的组件。
例如:
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();
});
如果有人能告诉我处理这个问题的最佳方法是什么,我将不胜感激。
我认为处理此问题的最简洁方法是从用户角色到处理器进行某种映射。
然后在您的函数中,您仍然需要检查是否设置了 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
});
我的网页有不同的 js 组件来处理不同的业务逻辑。我正在使用 RequireJS 来管理依赖项。我想动态加载所需的组件。
例如:
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();
});
如果有人能告诉我处理这个问题的最佳方法是什么,我将不胜感激。
我认为处理此问题的最简洁方法是从用户角色到处理器进行某种映射。
然后在您的函数中,您仍然需要检查是否设置了 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
});