Search code examples
javascriptextjsextjs5extjs6extjs6-modern

How to give config property to a view Item in Extjs 6?


In Extjs 6 how to assign a config property directly to a view either through binding or direct assignment?

Ext.define('App.view.main.Main', {
extend: 'Ext.Container',

config: {
    btnLabel: 'MyButton'
},

someOtherProperty:'xyz',

items: [{
    xtype:'button',

    //text:this.someOtherProperty,
    //text:this.btnLabel,
    //text:this.getBtnLabel(),

    //here accessing this throws error, while loading this refers to windows object and not the class... 
    width:'150px'
    }],
});

i can move the property to ViewModel and access it but my question is this, can't we assign the class level property to its child component?


Solution

  • Well, not like that you can't. The problem is that you're defining the items in the class prototype - which means you can't do anything specific to the instance there.

    That's what initComponent is for. I typically define my items attribute there, expressly for this purpose:

    Ext.define('App.view.main.Main', {
      extend: 'Ext.Container',
      config: {
        btnLabel: 'MyButton'
      },
      someOtherProperty:'xyz',
    
      initComponent: function() {
        // The config properties have already been transferred to the instance
        // during the class construction, prior to initComponent being called.
        // That means we can now call this.getBtnLabel()
        this.items = [
          { xtype: 'button',
            text: this.getBtnLabel(),
            width:'150px'
        }]
    
        // Call the parent function as well. NB: After this, items won't be
        // a simple array anymore - it gets changed into a collection of
        // components.
        this.callParent(arguments);
      }
    });
    

    In general, be careful adding objects in as class level properties, as they will be properties on the prototype and shared amongst all instances of that class.