to initComponent() or not to initComponent()

前端 未结 4 1890
温柔的废话
温柔的废话 2020-11-30 19:12

I struggle when building an app in ExtJS 4, and part of that is confusion on when to configure something in initComponent() and when not to...

For example, in Sencha

4条回答
  •  一向
    一向 (楼主)
    2020-11-30 19:26

    I've been searching for an answer to the same question when I ended up here and seeing these answers made me disappointed. None of these answer the question: initComponent() or constructor?

    It's nice to know that class config option objects are shared and you need to initialize/process them per instance, but the code can go into the constructor as well as the initComponent() function.

    My guess was that the constructor of the Component class calls initComponent() somewhere in the middle and I wasn't very wrong: Just had to look at the source code, it's actually AbstractComponent's constructor.

    So it looks like this:

    AbstractComponent/ctor:
    - stuffBeforeIC()
    - initComponent()
    - stuffAfterIC()
    

    Now if you extend a Component, you'll get something like this:

    constructor: function () {
      yourStuffBefore();
      this.callParent(arguments);
      yourStuffAfter();
    },
    initComponent: function () {
      this.callParent();
      yourInitComp()
    }
    

    The final order these get called in is:

    - yourStuffBefore()
    - base's ctor by callParent:
      - stuffBeforeIC()
      - initComponent:
        - base's initComponent by callParent
        - yourInitComp()
      - stuffAfterIC()
    - yourStuffAfter()
    

    So in the end it all depends on whether you want/need to inject your code between stuffBeforeIC and stuffAfterIC which you can look up in the constructor of the class that your are going to extend.

提交回复
热议问题