2012-01-31 44 views
0

我試圖從構造函數中將項目添加到Sencha Touch(2.0)面板子類。下面的代碼:通過構造函數向Sencha Touch Panel添加項目

Ext.define("MyApp.view.Icon", { 
     extend: "Ext.Panel", 
     config: { 
      layout: "vbox" //ensures caption appears directly below image 
     }, 
     constructor: function(cfg) { 
      this.add(
       //First we add the icon image 
       { 
        xtype: "image", 
        src: cfg.src, 
        width: cfg.width, 
        height: cfg.height 
       }, 
       //Then we add the icon caption 
       { 
        xtype: "panel", 
        html: cfg.caption 
       } 
      ); 
      return this; 
     } 
    }); 
    var anIcon = Ext.create("MyApp.view.Icon", { 
              src: "http://placehold.it/80", 
              width: 100, 
              height: 100, 
              caption: "My Icon"}); 

這樣做給我的錯誤:

Uncaught TypeError: Cannot call method 'has' of null

,它似乎從this.add()發起。我也試過this.self.add(),這也不起作用。有沒有辦法從構造函數中插入元素?

回答

2

它實際上是一個什麼樣@adis寫了一個組合:

constructor: function(config) { 
    this.callParent(config); 
    this.add({...}); 
} 

構造函數是在其上定義構造函數的性質。 callParent用於將配置對象傳遞給父構造函數。

0

我會使用initComponent()(請參閱API here)。 請注意API文檔中的以下行:

initComponent方法必須包含對callParent的調用,以確保父類的initComponent方法也被調用。

所以我會去:

initComponent: function() { 
    this.add(
      //First we add the icon image 
      { 
       xtype: "image", 
       src: cfg.src, 
       width: cfg.width, 
       height: cfg.height 
      }, 
      //Then we add the icon caption 
      { 
       xtype: "panel", 
       html: cfg.caption 
      } 
     ); 

    this.callParent(); 
} 

你有沒有嘗試過呢?

UPDATE 2012-01-30:對不起,我的壞,確實讀了!

你已經做到了正確的方式。你爲什麼在構造函數中返回this?我會通過調用this.initConfig(cfg)替換部分:

​​
+0

但initComponent似乎是ExtJS的一部分,而不是Sencha Touch 2.0。 http://docs.sencha.com/touch/2-0/ – Jay 2012-01-31 09:57:35

+0

不起作用。同樣的錯誤。我現在正在使用Beta 2。 – Jay 2012-02-17 10:09:04