Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Ext.apply in initComponent

Tags:

extjs

extjs4

A lot of code examples use Ext.apply when setting properties on a component in the initComponent method.

Example :

    initComponent: function(){
        Ext.apply(this, {
            items: {
                xtype: 'button'
            }
    })},

My question is, what is the difference in doing it that way, compared to doing it this way :

    initComponent: function(){
        this.items = {
            xtype: 'button'
        }
    }

For me it seems more readable that way. But am I missing something that I get from Ext.apply?

like image 456
Oliver Watkins Avatar asked Jun 25 '14 13:06

Oliver Watkins


People also ask

What is initComponent in Ext JS?

initComponent This method is invoked by the constructor. It is used to initialize data, set up configurations, and attach event handlers. beforeShow This method is invoked before the Component is shown. onShow Allows addition of behavior to the show operation.

What is render in Ext JS?

Column renderers give us the ability to customize the behavior and rendering of the cells inside a grid's panel. A renderer is tied to a particular column, and will run for each cell that it has to display/create in that column. In the Ext JS library, many renderers are already set inside the Ext.


2 Answers

Ext.apply() is used to simplify the copying of many properties from a source to a target object (most of the time the source and target objects have different sets of properties) and it can in addition be used to apply default values (third argument).

Note that it will not make deep clones! Meaning if you have a array or a object as property value it will apply the reference!

There is also a applyIf() which only copies properties that do not already exist in the target object. In some cases both implementations have also the benefit of dropping the reference of the copied object.

Note: Your second way won't work because you are missing this.

like image 167
sra Avatar answered Sep 21 '22 03:09

sra


initComponent: function(){
    items = {
        xtype: 'button'
    }
}

wouldn't initialize anything, you mean

initComponent: function(){
    this.items = {
        xtype: 'button'
    }
}

which does the same like your example using Ext.apply. But Ext.apply shows its power in more complex cases, e.g.

var x = {a: 1, c:3, e:5};
Ext.apply(x, {b:2, d:4, f:6});

console.log(x); // Object {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6}

This is often used to overwrite default options of components with given init parameters.

like image 22
Erich Kitzmueller Avatar answered Sep 18 '22 03:09

Erich Kitzmueller