我正在尝试使用函数在组件初始化时在组件内创建项目。
考虑以下因素:
Ext.define('mobi.form.Login',{
extend:'Ext.form.Panel',
config:{
items: [{
xtype: 'textfield',
name: 'Name',
label: 'Name'
}]
});
Ext.application({
viewport: {
layout:'fit'
},
launch: function(){
Ext.Viewport.add(Ext.create('mobi.form.Login'));
}
})
我正在尝试让 mobi.form.login
从在 initialize
上运行的函数生成其配置(或者我可以用来覆盖配置的任何内容)我指定)。
我知道Sencha touch 2有构造函数
和initialize
函数,但它们似乎都有arguments=[]
(例如一个空数组)
如果我在 ExtJS 4.x 中这样做,这或多或少是这样的:
Ext.define('mobi.form.Login',{
extend:'Ext.form.Panel',
initComponent:function(config){
config=Ext.apply({}.config,{});//make sure config exists
config.items= [{
xtype: 'textfield',
name: 'Name',
label: 'Name'
}]
Ext.apply(this, config);
this.callParent(arguments);
}
});
最佳答案
如果您想这样做,可以使用构造函数
或初始化
。
您将用于同步逻辑的构造函数,该逻辑将很快并且您希望在组件初始化之前发生。您可以通过构造函数的第一个参数访问配置:
Ext.define('MyComponent', {
extend: 'Ext.Component',
constructor: function(config) {
console.log(config);
this.callParent([config]);
}
});
Ext.application({
launch: function(){
Ext.create('MyComponent', { test: 1 })
// Will log out:
// {
// test: 1
// }
}
});
请记住,您总是需要在构造函数中使用config
/arguments
来callParent
。
在任何其他情况下,您应该使用initialize
,它在在所有配置都已初始化之后调用。 :) 我们在内部经常使用它来添加监听器。
initialize: function() {
this.on({
...
});
}
关于javascript - 在初始化函数中定义对象的项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9701370/