Auto Getters and Setters in Ext JS 4

Having read about the concept of Mutator and Accessor methods, today we will relate the concept to Ext JS 4. In the earlier versions of Ext JS, there was no in-built support for getter and setter methods. One had to write the getter and setter functions for common tasks like getting and setting a Window title. Each parameter would require writing individual getter and setter methods.

Ext.namespace('Refulz');

Refulz.MyWindow = Ext.extend(Ext.Window, {

title: 'Welcome to Ext JS App!',

getTitle: function() {

return this.title;

,

setTitle: function(Title) {

this.title = this.applyTitle(Title) ;

},

resetTitle: function() {

this.setTitle('Welcome to Ext JS App!');

},

applyTitle: function(Title) {

this.title = Title;

}

});

In the above example, we manually define the getter and setter methods. In addition, we defined a method to reset the Window title and a method to apply the new title. The applyTitle() method is called when the setTitle() method is called. Writing these common methods for each property can unnecessarily stretch the code. To provide solution for this problem, the Ext JS 4 comes with a config declaration.

Ext JS 4 – Config Declaration

The config declaration allows you to pass some of the configuration parameters to the class. These parameters can be accessed and modified at the runtime using the getter (accessor) and setter (mutator) methods.

For every property configured in the config declaration, Ext JS 4 auto generates 4 methods. The methods are generated for the get, set, reset and apply actions on the property. The convention for naming the methods is by suffixing the property to the method type. So, for the title property, the Ext JS 4 automatically generates getTitle(), setTitle(), resetTitle() and applyTitle() methods.

  1. The getTitle() will return the current title of the window.
  2. The setTitle() will set a new value for the title property of the window.
  3. The resetTitle() will reset the title to its default value.
  4. The applyTitle() is called for each setTitle() call.

To suit your custom requirements, Ext JS 4 permits you to override any of these methods. However, unlike the previous code snippet, the Ext JS 4 code will not require an explicit definition of the getter and setter methods. After passing title property to the config declaration, you can directly call the setTitle() method.

// define the class

Ext.define('Refulz.FirstWindow', {

extend: 'Ext.Window',

config: {

title: 'Welcome to the Ext JS App!'

},

applyTitle: function(Title) {

this.title = Title;

}

});

// create object of class

var win1 = Ext.create('Refulz.FirstWindow');

win1.setTitle('New Title Applied');

win1.show();

This reduces the coding time and the length of the code. The generalised convention of naming auto-generated functions leaves the room for overriding any of the methods by writing your custom code.