1

My webpage has different js components that handles different business logic. And I'm using RequireJS to manage dependencies. I want to dynamically load the component which is needed.

For example:

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

Really appreciate if anyone can tell me what is the best way to handle this.

1 Answer 1

3

I think the cleanest way to handle this is having a sort of mapping from user roles to processors. Then in your function, you still need to check that userRole is set, and a processor for the role is defined.

// 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
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help~ But i got a "Module name "***" has not been loaded yet for context" error from requirejs. So i have to change the processor = require(path) to require([path],function(processor){}) to have it fixed. Is it also correct?
Sure @RyanHu, I was considering the Node.js syntax, but yes, that's the way you load modules with requirejs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.