ExtJS in Review - xtype vs. alias

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

 

xtype

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

  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声明的布局是等同的:

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

  可以看到,在使用xtype的时候,我们可以不再标明类型的全名,进而减少了在使用它们时出错的可能,降低了维护的成本。

  而在定义一个类型的时候,我们可以指定该类型所具有的xtype:

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

 

alias

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

  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/

 

posted @ 2015-04-21 23:25  loveis715  阅读(2050)  评论(0编辑  收藏  举报