Extjs: extend class via constructor or initComponent?

前端 未结 3 439
小鲜肉
小鲜肉 2021-02-01 19:05

In extjs you can always extend an extjs class via the constructor(). For classes derinving from Component you can also extend via initComponent(

3条回答
  •  醉话见心
    2021-02-01 19:17

    Let me try an updated answer in terms of ExtJS versions 4.0-4.2 and beyond.

    The constructor() is the object/class before create method. And initComponent() is the component before show method.

    constructor: function(config) {
      // ctor #1 - insert code here to modify config or run code to inject config
      // probably the cheapest place to make changes - before anything has been built
    
      this.callParent(arguments);
    
      // ctor #2 - insert code here if you need to make changes 
      // after everything has been rendered and shown, IIUC
    },
    initComponent: function() {
      // this function runs between ctor #1 and ctor #2
    
      // initComponent #1 - the UI component object tree is created,
      // (this object and child objects from config { items: [{...}]})
      // but they have not yet been rendered to DOM or shown.
    
      this.callParent(arguments);
    
      // initComponent #2 - I believe this is equivalent to ctor #2, 
      // I would prefer ctor as it is more universal.
    }
    

    Panels with children or complex layout you'll probably need to use initComponent, because you'll need to inspect and manipulate the components (the UI object graph).

    But for individual form elements (combobox, button, etc.) then I stick with constructor, which I believe is lighter (before any complex object construction or DOM changes) and is more universal. IOW constructors can be used for simple UI, models, and data stores; the latter two can't use initComponent.

    So I only use initComponent when there's a reason to do so. Often when I write an initComponent function I'm trying to manipulate child UI objects, and my next step is to extract that child control into its own Ext.define(), the move the custom code to run in the child control class, which removes the complex init from the parent panel. This process I've repeated 4 times in my latest page.

提交回复
热议问题