moh*_*han 12 extjs extjs4.1 sencha-architect extjs4.2
谁能告诉我initComponentextjs4.1 中该函数的用途是什么?请举个例子
谢谢
rix*_*ixo 12
该方法类似于constructor组件.它由true调用constructor,并且是一个非常好的钩点,用于自定义组件的初始化(如名称中所述!).
除非在极少数情况下,您应该覆盖initComponent而不是constructor因为更基本的初始化已经发生.最值得注意的是,传递给构造函数的配置对象已经合并到对象中.
假设您要自定义组件的配置,例如设置它width.如果您尝试在构造函数中执行此操作,则必须首先检查我们是否已经传递了配置对象(以避免尝试设置属性undefined),并且您将覆盖配置对象,是不好的做法.如果您将选项设置为this,则可能会被配置对象覆盖.如果更改config对象中的值,则修改对象,从而破坏调用代码的期望(即重用config对象会产生意外结果).在initComponent,值永远是this.width,您不必担心配置.
另一个有趣的点是,创建initComponent子组件(用于容器),存储,视图,模板等的位置.因此,在调用超类initComponent方法之前,您可以采取行动确保它们尚未被使用或需要(例如添加项目,创建商店等).另一方面,一旦调用了super方法,就可以保证所有这些依赖项都已创建并实例化.例如,这是向依赖项添加侦听器的好地方.
话虽如此,请记住,没有进行渲染initComponent.已创建和配置子组件,但尚未创建其DOM元素.要影响渲染,您必须使用渲染相关事件或查找afterRender或onRender方法...
这是一个插图摘要:
constructor: function(config) {
// --- Accessing a config option is very complicated ---
// unsafe: this may be changed by the passed config
if (this.enableSomeFeature) { ... }
// instead, you would have to do:
var featureEnabled;
if (config) { // not sure we've been passed a config object
if (Ext.isDefined(config.featureEnabled)) {
featureEnabled = config.featureEnabled;
} else {
featureEnabled = this.enableSomeFeature;
}
} else {
featureEnabled = this.enableSomeFeature;
}
// now we know, but that wasn't smooth
if (featureEnabled) {
...
}
// --- Even worse: trying to change the value of the option ---
// unsafe: we may not have a config object
config.enableSomeFeature = false;
// unsafe: we are modifying the original config object
(config = config || {}).enableSomeFeature = false;
// cloning the config object is safe, but that's ineficient
// and inelegant
config = Ext.apply({enableSomeFeature: false}, config);
// --- Super method ---
this.callParent(arguments); // don't forget the arguments here!
// --------------------
// here initComponent will have been called
}
,initComponent: function() {
// --- Accessing config options is easy ---
// reading
if (this.enableSomeFeature) { ... }
// or writing: we now we change it in the right place, and
// we know it has not been used yet
this.deferRender = true;
// --- Completing or changing dependant objects is safe ---
// items, stores, templates, etc.
// Safe:
// 1. you can be sure that the store has not already been used
// 2. you can be sure that the config object will be instantiated
// in the super method
this.store = {
type: 'json'
...
};
// --- However that's too early to use dependant objects ---
// Unsafe: you've no certitude that the template object has
// already been created
this.tpl.compile();
// --- Super method ---
this.callParent();
// --------------------
// Safe: the store has been instantiated here
this.getStore().on({
...
});
// will crash, the element has not been created yet
this.el.getWidth();
}
Run Code Online (Sandbox Code Playgroud)