1

I have 100s of classes from which I have to require Dojo class depending upon user selection. To boil it down, I have to require a Dojo class on basis of string value selected by user.

For instance if user selects a truck icon, I get truck and I have a class named truck.

Sync loader style can load it like

var userSelection = "Truck";
var myVeh = require("Vehicles/"+userSelection); 
var veh = new myVeh('Truck 4', 15000); 
veh.honk();

Dojo good practice recommends using AMD loader to make sure classes is loaded before you make use of it.

require([
        "Vehicles/Truck",
        "dojo/domReady!"
      ], function(
        Truck
      ) { ...... });

I want to stick with AMD style loading but

how can I require classes in AMD style from a variable value to be used in callback?

What if I load with first non-AMD method? What are pros and cons?*

I have tried Use dynamic variable names in JavaScript and Dynamic variables names in javascript. They all suggest window and [] methods but none worked for me.

I am using Dojo 1.10.4

Community
  • 1
  • 1

1 Answers1

2

01) You can require your dojo classes (in the following example module Truck.js) using require, after the module is loaded a callback is executed passing as argument your dojo class.

Below an example which demonstrate require and a callback function.

require('Vehicles/Truck', function(Truck){
    var myTruck= new Truck('Truck 4', 15000);
});

You can specify more dynamically which module to load using:

var userSelection = 'Truck';
require('Vehicles/' + userSelection, function(Truck){
    var myTruck= new Truck('Truck 4', 15000);
});

02) Supposing your Truck.js is a AMD module, both your approaches (as mentionated in your question) are actually using AMD loading.

You can read more about require here: https://dojotoolkit.org/reference-guide/1.10/dojo/require.html

GibboK
  • 71,848
  • 143
  • 435
  • 658