In Javascript ES6, how do we load classes dynamically ?
I'm building an asset manager and in the class 'asset' below there is a load()
method that uses the JQuery function $.getScript()
to load the file security.js. Nonetheless the file security.js does load as I am able to see the Ajax call and the responses for it. However I am unable to initialize the class by,
neither
yellow = new asset_security();
nor
let script = new window['asset_'+s['screen']]();
My Example:
class asset {
constructor() {
this.include = ['general','header','menu'];
this.css = [];
this.js = [];
// Create Defaults for the app
this.css['general'] = [];
this.js['general'] = [];
this.css['header'] = [];
this.js['header'] = [];
this.css['menu'] = [];
this.js['menu'] = [];
// this.css['general'][this.css['general'].length] = 'initial.css';
// this.js['general'][this.js['general'].length] = 'controller/initial.js';
// this.css['header'][this.css['header'].length] = 'header/header.css';
// this.js['header'][this.js['header'].length] = 'header/controller/header.js';
// this.css['menu'][this.css['menu'].length] = 'menu/header.css';
// this.js['menu'][this.js['menu'].length] = 'menu/controller/menu.js';
}
load() {
let s = new status(0);
/**
* @param data ~ Content of the script returned
* @param textStatus ~ Verbal response to success or fail
* @param browser ~ browser.status returns the 200/404/500 statuses
*/
$.getScript( "/js/asset/"+s['screen']+'.js', function( data, textStatus, browser ) {
var exist = false;
try {
exist = (typeof 'asset_'+s['screen'] === 'function');
} catch (e) {}
if ( exist ) {
//TODO: figure out how to load class dynamically
/*
let script = new window['asset_'+s['screen']]();
script.load();
script.render();
*/
}
});
}
The response that I get from the console state :ReferenceError: asset_security is not defined
What is the proper way to initialize the class after $.getScript()
run ?
This is how the asset_security class looks like:
class asset_security extends asset {
constructor() {
super();
this.className = 'asset_security';
this.include = ['security'];
this.css['security'] = [];
this.js['security'] = [];
}
load() {
// this.css['security'][this.css['security'].length] = 'security/formLogin.css';
// this.js['security'][this.js['security'].length] = 'security/controller/security.js';
// this.js['security'][this.js['security'].length] = 'security/modal/screen.js';
// this.js['security'][this.js['security'].length] = 'security/view/screen.js';
}
}