Saturday, December 8, 2012

ExtJS 4 –Classes–Statics

In previous post, we looked at creating classes. Now we will look at creating statics – functions and properties. ExtJS provides a simple way to create statics and methods.

The properties and methods should be given to a statics config inside the class.

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

var init = function () {
var newPerson = Ext.create('Training.class.Person', {
firstname:'John'
});

// Setting count value
Training.class.Person.count = 10;
Training.class.Person.increment();
console.log("Count after increment is " + Training.class.Person.getCount());
console.log("Count from method " + newPerson.getOuterCount());

};

Ext.onReady(init);

 


In the above example, we are defining a static varaible “count” and two static method “getcount” and “incement”. To access the count property, we are using “Training.class.Person.count” no need of instance. Similarly for method “Training.class.Person.increment() and getCount()”.


To access the static variable in a non static method use “this.static().propertyname”. We are doing that in “getOuterCount” method. This is called by “newPerson.getOuterCount()” from the init function.


The demo is available here

No comments:

Post a Comment