2013-05-05 86 views
2

我想在處理之前準備一些Json Store到callParent(),然後它會拋出一個錯誤。ExtJS 4 - 異步回調callParent拋出異常

但是,me.callParent()可以在沒有異步回調的情況下正常工作。

Ext.define('My.desktop.AppExt', { 
    extend: 'Ext.ux.desktop.App', 

    someStore: null, 

    init: function() { 
     var me = this; 
     me.someStore = Ext.create('My.store.SomeStore'); 
     me.someStore.load({ 
      scope: this, 
      url: 'some/json/url', 
      callback: function(records, opt, success) { 
       if (success) { 
        me.callParent(); // BOOM! ERROR HERE 
       } 
      } 
     }); 
    } 
}); 

ERROR:

未處理的異常在線路4245,在//localhost/js/ext-all-debug.js

0x800a138f柱17 - JavaScript的運行時錯誤:

無法獲取屬性「超類」的未定義或空引用

回答

5

callParent依賴上下文來調用正確的方法,所以如果你沒有真正把它稱爲「直接」從子類的方法,你需要手動調用它:

Ext.define('A', { 
    foo: function(){ 
     console.log('foo', 'a');  
    } 
}); 

Ext.define('B', { 
    extend: 'A', 
    bar: function(){ 
     this.self.superclass.foo.call(this);  
    } 
}); 

Ext.onReady(function(){ 
    var o = new B(); 
    o.bar(); 
}); 
+0

謝謝你的快速響應!我想知道異步調用,除了callParent()之外,是否還有其他的功能在我應該知道的相同情況下是相似的? – Tom 2013-05-05 11:26:50

+1

'callParent'詢問調用函數以找出需要調用的內容。所以,看起來像一個「魔術」電話的任何東西都使用相同的技術。 – 2013-05-05 11:33:58

0

一個我知道的方法是使用額外的參數,指示該父方法應該叫:

init: function(callParent) { 
    if (callParent) { 
     this.callParent(); 
    } 
    var me = this; 
    me.someStore = Ext.create('My.store.SomeStore'); 
    me.someStore.load({ 
     scope: this, 
     url: 'some/json/url', 
     callback: function(records, opt, success) { 
      if (success) { 
       this.init(true); 
      } 
     } 
    }); 
} 

如果使用this.self.superclass.init.call(本)這將是確定只有等到你的類會有人創建子。 this.self.superclass指向實例的超類,所以它將指向My.desktop.AppExt而不是Ext.ux.desktop.App。

更新時間:24.08.2016:發佈更智能的解決方案(請參閱我的另一個答案)。

0

用於此目的的最好的解決辦法是讓鏈接parentMethod像在callParent()函數,但沒有調用它:

/** 
* Returns reference to the parent class method. Works as {@link Ext.Base#callParent}, but doesn't invoke the 
* method. 
* @return {Function} Parent class method. 
*/ 
getParentMethod: function() { 
    var method, 
     superMethod = (method = this.getParentMethod.caller) && (method.$previous || 
      ((method = method.$owner ? method : method.caller) && method.$owner.superclass[method.$name])); 
    return superMethod; 
}, 


sampleMethod: function() { 
    var parentMethod = this.getParentMethod(); 
    var parentArguments = arguments; 
    someAsyncFunc(function() { 
     parentMethod.apply(this, parentArguments); // calls parent.sampleMethod(...) 
    }, this); 
}