2012-12-29 33 views
1

我創建了自己的「庫」,因爲我想讓代碼保持乾爽。這個想法只是擴展SimpleController併發送一個名字,以便它可以一般地加載已經創建的商店和視圖,但在我的控制檯中,我收到一條消息,說明nameOfController未定義。商店中未定義的變量:[]和視圖:[] - Ext-JS 4.1.1a

1.)在這個例子中,爲什麼nameOfController是undefined?

2.)我知道如何擴展SimpleController,但是什麼時候初始化nameOfController?在init()函數中?是否有一些函數甚至在加載商店之前執行:[]和views:[]?

Ext.define('MyApp.controller.SimpleController', { 
    extend: 'Ext.app.Controller', 

    nameOfController: "", 


    stores: ['MyApp.store.' + this.nameOfController], 
    views: ['MyApp.view.' + this.nameOfController + '.Index'] 

編輯:(實施例延伸的)

Ext.define('MyApp.controller.Users', { 
    extend: 'MyApp.controller.SimpleController', 

    nameOfController: "Users" //I want to this nameOfController 
           //changes the one in superclass 
}); 
+0

表達'this.nameOfController'立即評估,而是僅創建了「nameOfController」屬性* *後立即數,整個對象求值,以及相應的對象被創建。 –

回答

1

您可以爲控制器定義構造函數。例如:

Ext.define('MyApp.controller.SimpleController', { 
    extend: 'Ext.app.Controller', 
    nameOfController: "", 

    //stores: ['MyApp.store.' + this.nameOfController], 
    //views: ['MyApp.view.' + this.nameOfController + '.Index'] 

    constructor: function(config) { 
     var name = config.nameOfController; 

     config.stores = config.stores || []; 
     config.views = config.views || []; 

     config.stores.push('MyApp.store.' + name); 
     config.views.push('MyApp.view.' + name + '.Index'); 

     this.callParent(arguments); 
    } 
}); 
+0

謝謝你的迴應。這看起來不錯。我會試試看。 :) –

0

在定義對象時,該對象不是this

你可以使用匿名的自我調用函數:

Ext.define("MyApp.controller.SimpleController",(function(name) { 
    return { 
    extend: 'Exp.app.Controller', 
    nameOfController: name, 
    stores: ['MyApp.store.'+name], 
    views: ['MyApp.view.'+name+'.Index'] 
    }; 
})("Users")); 
+0

感謝您的回覆,但我認爲Lolo的解決方案更清潔。如果他的解決方案不起作用,我會試試你的。 :) –

0

這會工作:

var name = "Users"; 

Ext.define('MyApp.controller.SimpleController', { 
    extend: 'Ext.app.Controller', 

    nameOfController: name,  

    stores: ['MyApp.store.' + name], 
    views: ['MyApp.view.' + name + '.Index'] 
}); 

因此,該字符串存儲在外部變量。

+0

謝謝你的迴應。我如何將變量nameOfController發送給超類?用this.callParent()?我編輯了我的問題,所以如果你看,我會很感激。 –

+0

@DavorLozic我不明白你的模式。你爲什麼要在'Users'中設置'SimpleController'的名字? –

+0

因爲在我的SimpleController中將所有我想在所有控制器中共享的邏輯,但唯一的區別是「名稱」。比方說,**用戶**,**國家**,**工作人員** ......他們都對數據庫有CRUD,而且邏輯在任何地方都是一樣的。 –