ExtJS in Review - xtype vs. alias

  今天在帮一个兄弟检查一段自定义控件的代码时以为他对xtype以及alias的使用和ExtJS各示例代码的使用有较多的不一致,而我本身也不是很清楚使用这两个属性时的最佳方法。所以在回家后整理出了这样一篇文档。一方面用来标准化咱们本身的代码,另外一方面也共享给你们,毕竟对这两个属性进行详细讨论的资料几乎没有。html

 

xtypeapi

  首先来看看xtype的定义。在ExtJS的官方文档中是这样对它进行定义的:ide

  This property provides a shorter alternative to creating objects than using a full class name. Using xtype is the most common way to define component instances, especially in a container.布局

  也就是说,在定义一个类的时候,若是咱们指定了它的xtype,那么咱们就能够经过这个xtype,而不是类型的全名来建立这些类型。例如对于下面的布局声明:性能

1 items: [
2     Ext.create('Ext.form.field.Text', {
3         fieldLabel: 'Foo'
4     }),
5     ……
6 ]

  其与如下使用xtype声明的布局是等同的:this

1 items: [
2     {
3         xtype: 'textfield',
4         fieldLabel: 'Foo'
5     },
6     ……..
7 ]

  能够看到,在使用xtype的时候,咱们能够再也不标明类型的全名,进而减小了在使用它们时出错的可能,下降了维护的成本。spa

  而在定义一个类型的时候,咱们能够指定该类型所具备的xtype:code

1 Ext.define('MyApp.PressMeButton', {
2     extend: 'Ext.button.Button',
3     xtype: 'pressmebutton',
4     text: 'Press Me'
5 });

 

aliascomponent

  而在文档中,alias的定义则以下所示:orm

  List of short aliases for class names. An alias consists of a namespace and a name concatenated by a period as <namespace>.<name>

namespace - The namespace describes what kind of alias this is and must be all lowercase.

name - The name of the alias which allows the lazy-instantiation via the alias. The name shouldn't contain any periods.

  在一个类型定义中,咱们能够指定它所使用的alias:

1 Ext.define('MyApp.CoolPanel', {
2     extend: 'Ext.panel.Panel',
3     alias: ['widget.coolpanel'],
4     title: 'Yeah!'
5 });

  而对这个类型的使用也很是简单,在xtype中标示该alias便可:

1 Ext.widget('panel', {
2     items: [
3         {xtype: 'coolpanel', html: 'Foo'},
4         {xtype: 'coolpanel', html: 'Bar'}
5     ]
6 });

 

xtype vs. alias

  能够看到,xtype和alias有点像,是吧?那么它们两个有什么区别,何时用xtype,何时用alias呢?

  上面的示例也展现了一个比较有趣的事情,那就是经过alias所定义的别名“coolpanel”能够直接经过xtype引用。也就是说,xtype和alias实际上能够在必定程度上通用的。

  最终我在ClassManager类的源码中找到了一系列证据。简单地说,xtype是存在于widget命名空间下的alias。若是为一个新的UI组成声明了它的xtype,那么就等于在widget命名空间下为其声明了一个alias。例如咱们也能够经过下面的代码定义刚刚看到的CoolPanel类:

1 Ext.define('MyApp.CoolPanel', {
2     extend: 'Ext.panel.Panel',
3     xtype: ‘coolpanel’,
4     title: 'Yeah!'
5 });

  总的来讲,为一个UI组成指定一个xtype实际上就等于为其指定一个在widget命名空间下的alias。可是alias所能覆盖的类型范围要比xtype广得多。一个alias不单单能够用来声明命名空间为widget的各个类型,更能够在plugin,proxy,layout等众多命名空间下声明类型。

  而在Sencha论坛中,一位开发人员也解释了为何在alias已经存在的状况下定义一个额外的xtype。这仅仅是为了提升性能。在ExtJS的内部实现中经常须要将alias中的命名空间剥离才能获得所须要建立的widget类型。在xtype的帮助下,ExtJS能够摆脱掉耗时的字符串分析工做,从而提升性能。

  所以在定义一个自定义widget的时候,咱们应当使用xtype,而在定义其它组成时,咱们就不得不使用alias了。因为全部的widget使用同一个命名空间,所以咱们须要在为自定义widget指定xtype时标示一个前缀,例如在项目egoods中定义的一个自定义button的xtype就应为egoods-button。

 

References

  本文章中全部示例均来自于ExtJS官方文档:http://docs.sencha.com/extjs/5.1/5.1.0-apidocs/

相关文章
相关标签/搜索