我看到兩個選項開箱:
- 提出,將調用init函數的最後準備回調
- 您可以創建一個定時器來檢查當對象準備的功能。
第二種選擇示例代碼:
function myInitFunction() {
// some code that doesn't need the component... if any
executeWhenReady('componentId', executeCodeWhichNeedsComponent);
function executeCodeWhichNeedsComponent(component) {
// this is just the code where you actually need the component
// an example:
component.addChild(new ChildComponent);
component.show();
// etc...
}
}
function executeWhenReady(cmp, fn) {
if (! Ext.get(cmp)) {
setTimeout(function() { executeWhenReady(cmp, fn); }, 20);
} else {
fn(Ext.get(cmp));
}
}
我只是想補充一點,裏面executeCodeWithComponent
你不會有相同的this
。如果你想保留它,讓我知道,我會更新代碼。
我知道這兩種解決方案都不是那麼幹淨,但最好的選擇是重構你的代碼,你說你不能這樣做。
我會看看我是否可以使用一般的myInitFunction,但我懷疑它也可能失敗。我認爲這是一個非常常見的情況,組件彼此依賴,並且不能保證初始化順序,所以我想查看有關executeCodeWithComponent解決方案的詳細信息。謝謝btw。 – hazimdikenli
好的,我已經大量編輯了我的第一篇文章,再看一遍。現在executeWhenReady是一個可以在任何地方使用的函數(並且它實際上應該可以工作 - 最初的實現沒有)。另外,我對executeCodeWithComponent做了一些評論,我希望它的目的很明確 - 它只包含需要組件的代碼(即它是你的代碼)。 – deviousdodo