extjs4 define的一些问题
今天同bryntum.com的Mats讨论了一些Extjs4的问题:
1: Ext.define中的属性定义要注意,不要用object或array类型
例如:
Ext.define('MyPanel', {
extend : 'Ext.Panel',
fd1:{
p1:1,
p2:2
}
});这样定义的类MyPanel创建的所有实例的fd1属性会指向同一个json对象。这是因为目前Extjs的实现的属性copy没有深拷贝,同样的问题存在于通过config定义的属性。
解决方案:
constructor: function() {
arguments[0].fd1 = {p1:1,p2:2};
this.callParent(arguments);
}即通过在构造器中设置实例属性来达到目的。
Mats说这不是bug,而是prototype本身就是这样的。但是我觉得真是容易上当,这样的解决方案也很不方便。
2: 怎样在config中设置scope?
Ext.define('MyPanel', {
extend : 'Ext.Panel',
sayHello : function() { console.log('Hello world'); },
tbar : [
{
text : 'Click to say hello',
handler : this.sayHello,
scope : this
}
],
... // stores, columns defined below
});
上面代码的错误是scope:this,中的this在此语境下是window,但是怎样将scope设置为MyPanel实例?
解决方法原理同上面,在构造其中将this传入。
Ext.define('MyPanel', {
extend : 'Ext.Panel',
sayHello : function() { console.log('Hello world'); },
constructor : function() {
arguments[0].tbar = [
{
text : 'Click to say hello',
handler : this.sayHello,
scope: this
}
];
this.callParent(arguments);
}
});
另外还有其他几点:
a. 使用事件的优化(性能方面):
a1. 对于列表li的事件,可由其上级元素ul监听,通过switch来判断具体由哪个触发。
a2. 举个例子,在store的load事件中来操作grid,但是要注意,grid可能被销毁,而store却可能存在。所以这里要注意处理。
b. instanceof 右边的类需要判断是否存在,对于Extjs4动态加载的情况这一点很重要。

