Ext JS 4 gives us the ability to only load the parts of the framework we need, as and when we need them. In this recipe, we will explore how to use the framework to automatically load all our class dependencies on the fly.
We are going to use the Vehicle
and Plane
classes that we created in the Using inheritance recipe earlier to demonstrate dynamic loading.
Configure the
Ext.Loader
class to enable it and map our namespaces to a physical path. This should be added before yourExt.onReady
call:Ext.Loader.setConfig({ enabled: true, paths: { 'Cookbook': 'src/Cookbook' } });
Create individual files in the
src/Cookbook
folder for theVehicle
andPlane
classes, naming each the same as the class name (excluding the namespace).Call the
Ext.require
method, inside ourExt.onReady
function, passing in the class we need, and a callback function, which is executed after the class and all its dependencies have loaded, containing our code:Ext.require('Cookbook.Vehicle', function(){ var van = Ext.create('Cookbook.Vehicle', 'Ford', 'Transit', 60); van.travel(200); });
Execute the code and monitor your Developer Tools console and HTML tabs and you will see the
Ext.define
's callback being displayed and the new script tag being injected into the HTML:
The initial configuration of the Ext.Loader
class is vital for our classes to be loaded correctly, as it defines how class names are mapped to file locations so the Loader
class knows where to find each class it is required to load. It also highlights the need for strict naming conventions when it comes to creating your files.
In our example, the paths configuration tells the Loader that any required classes within the Cookbook
namespace should be loaded from the src/Cookbook
directory.
We then call the Ext.require
method, (an alias of the Ext.Loader.require
method) which takes the class name specified and resolves its URL based on the paths configuration, and if it hasn't already been loaded previously, injects a script tag into the HTML page to load it. Once this load has happened the specified callback function is executed where you can create instances of the class with the knowledge that it has been fully loaded.
The Ext.require
method accepts either a single or array of string values that will all be loaded prior to the callback being executed.
One of the great things about the Ext.Loader
class is that it is recursive and won't stop until all the files needed by the original required classes are loaded. This means that it will load all classes referenced in the extend, mixins, and requires configuration objects.
We will demonstrate this by creating an instance of Cookbook.Plane
, which extends the Cookbook.Vehicle
class. If we execute the following code, and monitor your developer tool as we did before, we will see both classes being loaded and created:
Ext.require('Cookbook.Plane', function(){ var plane = new Ext.create('Cookbook.Plane', 'Boeing', '747', 500, 35000); plane.travel(200); });