0

コンストラクターから Sencha Touch (2.0) パネルの子クラスに項目を追加しようとしています。以下のコード:

    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()、これもうまくいきません。コンストラクターから要素を挿入する方法はありませんか?

4

2 に答える 2

2

これは実際には@adisが書いたものの組み合わせです:

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

コンストラクターは、コンストラクターが定義されているプロパティです。また、callParentは、構成オブジェクトを親コンストラクターに渡すために使用されます。

于 2012-03-06T08:41:06.780 に答える
0

を使用します (ここでinitComponent()API を参照してください)。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();
}

これを試しましたか?

UPDATE 2012-01-30:申し訳ありませんが、正確に読みました!

あなたはそれを正しい方法で行いました。なぜthisコンストラクタに戻っているのですか?その部分を次のように呼び出して置き換えthis.initConfig(cfg)ます。

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
            }
        );
        this.initConfig(cfg);
    }
于 2012-01-31T08:00:23.830 に答える