我有几个月开发Extjs web应用程序的经验。我遇到了这个问题:
当我重写一个类时,我修改了该方法并遵循前面的实现并调用callParent()
。重写部分工作,但callParent()
调用旧的实现。
我的重写代码
Ext.override(Ext.layout.component.Draw, {
finishedLayout: function (ownerContext) {
console.log("new layouter being overriden");
this.callParent(arguments);
}
});
要重写的Extjs类方法:
finishedLayout: function (ownerContext) {
var props = ownerContext.props,
paddingInfo = ownerContext.getPaddingInfo();
console.log("old layouter being overriden");
this.owner.setSurfaceSize(props.contentWidth - paddingInfo.width, props.contentHeight - paddingInfo.height);
this.callParent(arguments);
}
在控制台中,我可以看到首先新的layouter打印出消息,然后是旧的layouter实现…我放置了一个断点并回溯调用堆栈,新layouter的callParent()
调用旧的layouter。我需要调用父类,而不是被重写的方法。
你知道怎么解决这个问题吗?
如果您使用ExtJS 4.1.3或更高版本,您可以使用this.callSuper(arguments)
"跳过"覆盖的方法并调用超类实现。
该方法的ExtJS文档提供了如下示例:
Ext.define('Ext.some.Class', {
method: function () {
console.log('Good');
}
});
Ext.define('Ext.some.DerivedClass', {
method: function () {
console.log('Bad');
// ... logic but with a bug ...
this.callParent();
}
});
Ext.define('App.patches.DerivedClass', {
override: 'Ext.some.DerivedClass',
method: function () {
console.log('Fixed');
// ... logic but with bug fixed ...
this.callSuper();
}
});
和评论:
补丁方法不能使用callParent来调用父类方法,因为这将调用包含错误的被覆盖的方法。换句话说,上面的补丁只会在控制台日志中产生"Fixed"然后"Good",而使用callParent会产生"Fixed"然后"Bad"然后"Good"
不能使用callParent
,但可以直接调用父类方法。
GrandparentClass.prototype.finishedLayout.apply(this, arguments);
这是一个更通用的(如果有些脆弱)方法。
this.superclass.superclass[arguments.callee.$name].apply(this, arguments);