2012-01-31 18 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を使用して、configオブジェクトを親コンストラクタに渡します。

0

私はinitComponent()を使用します(API hereを参照)。 注APIドキュメント上でこの行:

はinitComponentメソッドは、親クラスのinitComponentメソッドとも呼ばれていることを確実にするためにcallParentへの呼び出しが含まれている必要があります。

だから私はのために行くだろう:

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(); 
} 

は、あなたはこれを試してみましたしましたか?

更新日2012-01-30:申し訳ありませんが、私の悪い、正確に読み取った!

これは正しい方法でした。なぜコンストラクタにthisを返すのですか?私はthis.initConfig(cfg)を呼び出すことによって、その部分を置き換えます:

​​
+0

しかし、initComponentはSencha Touch 2.0ではなくExtJSの一部であるようです。 http://docs.sencha.com/touch/2-0/ – Jay

+0

動作しません。同じエラー。私は今ベータ2を使用しています。 – Jay

関連する問題