Saturday, December 8, 2012

ExtJS 4–Classes–Dynamic Loading

 

In previous posts, we have been looking at defining classes and statics. The process was to define a class in the JavaScript file and access it. So we include individual JavaScript file (which define the class) to the page. But in dynamic class loading, the ExtJS Loader (Ext.Loader) does a dynamic resolution of classes based on the configured folder structure. The process is two part

  1. Define the classes in respective js file location in correct folder structure
  2. Enabling dynamic loading and setting the path resolution. For example,
// Configure the loader 
Ext.Loader.setConfig({
enabled:true,
paths:{
package1:'path to package1',
package2:'path to package2'
}
});

The code above enables the dynamic loading and set the package resolution. Let take the Person class define in previous post


Step 1


The process is to move the Person class to “person.js” located in following folder structure “training/classes/person.js” as shown below.


BLOG- 9.49.58 PM


In my case, I am placing person.js in “js/applicaiton/training/classes” folder. The code of “person.js” is given below.

// Define a person class
Ext.define('Training.class.Person', {
// list of properties, setter and getter of all the property will
// be available on instantiation.
config:{
firstname:'',
lastname:'',
age:'',
city:'',
country:''
},
constructor:function (config) {
this.initConfig(config);

},
applyFirstname:function (value) {
return value.toUpperCase();
},

getLongName:function () {
return this.firstname + "," + this.lastname;
},
statics:{
count:'',
getCount:function () {
return this.count;
},
increment:function () {
this.count++;
}
},
// refer the static property by this.statics().count
getOuterCount:function () {
return this.statics().count;
}
});

The code is just the copy from previous post.


Step 2


The next step is to configure the loader so that when we create object for Person class it is able to resolve the class. So, we need to configure “Training” package to “js/application/training” folder. The code is as defined below.

 Ext.Loader.setConfig({
enabled:true,
paths:{
'Training':'js/application/training'
}
});

Now we need not include person.js in the page where we create person object. The loader will resolve the class to load.


The page code is given below.


var init = function () {
// Configure the loader
Ext.Loader.setConfig({
enabled:true,
paths:{
'Training':'js/application/training'
}
});

var newPerson = Ext.create('Training.class.Person',{
firstname:'John',
lastname:'Doe'
});
console.log("First name is "+newPerson.getFirstname());
};

Ext.onReady(init);

We have only this code in page. When we instantiate using Ext.create(‘Training.class.Person’), the loader will dynamically load the Person.js as shown below.


BLOG- 10.02.55 PM


As we see the loaded does a load when the class is required.


The demo can be found here

No comments:

Post a Comment