2014-02-12 86 views
1

我試圖導航Sencha類系統,似乎在這方面失敗。Sencha Touch - 爲什麼在我的自定義組件中未定義此功能?

我有一個Carousel,我也添加了組件。我有一個帶有記錄的商店,並且我正在循環查看記錄,並在每次迭代中將自定義組件添加到傳送帶。下面是代碼...

var carousel = Ext.create("Ext.Carousel", { 
     fullscreen: true 
    }); 

    sights.each(function(sight, index, length){ 
     carousel.add(Ext.create("Parks.view.ImageView", { 
      imageName: sight.get("img"), 
      titleName: sight.get("name") 
     })); 
    }); 

我的自定義組件具有以下代碼,但由於getImageName()函數而無法執行。它抱怨它沒有被定義。但是,基於我對Sencha類結構的理解,它應該由構造函數在初始化時定義?

Ext.define("Parks.view.ImageView", { 
    extend: "Ext.Panel", 
    fullscreen: true, 

config: { 
    imageName: "", 
    titleName: "" 
}, 

constructor: function(config){ 
    this.initConfig(config); 
}, 

items: [ 
    { 
     xtype: "img", 
     layout: "fit", 
     src: getImageName() 
    } 
] 

});

回答

2

在代碼中隱藏另一個錯誤是有錯誤的。

首先,它應該是this.getImageName()。但即使如此,它不會工作,因爲你需要this指向你的類的實例來調用這個方法(也許你應該閱讀關於Javascript的範圍有點......這是一個相當辛辣的主題!)。

在這裏,你必須意識到你的函數將以前構造,甚至Ext.define爲此事之前被調用(因爲需要爲在items對象的src財產的方法的返回值作爲參數傳遞給Ext.define的對象的屬性)。

當你需要做一些處理(即執行函數)來創建一個組件的配置,覆蓋其initialize方法,像這樣:

Ext.define("Parks.view.ImageView", { 
    extend: "Ext.Panel", 
    fullscreen: true, 


    config: { 
     imageName: "", 
     titleName: "", 
     layout: "fit" 
    }, 

// This is not needed, and it will break everything. You're extending from 
// a class that already calls initConfig for you. And you don't call the parent 
// method, so you're completely removing the component initialization cycle. 
// 
// constructor: function(config){ 
//  this.initConfig(config); 
// }, 

    initialize: function() { 

     // you should test that you have a value in imageName before using it 
     this.add({ 
      xtype: "img", 
      layout: "fit", 
      src: this.getImageName() 
     }); 

     // this one is probably not needed because the parent method is empty (it is 
     // is what Ext calls a template method), *but* it is more safe to call it 
     // anyway -- in case some override put some code in this method upper in 
     // the class hierarchy 
     this.callParent(arguments); 
    } 
}); 

編輯:我的答案適用於ExtJS的,它並沒有與觸摸...

+0

這工作,一旦你添加一個佈局面板,就像我上面編輯它 – bluedevil2k