您使用控制器按需的最佳方式是动态加载它们并在需要时创建控制器实例。另外你需要把你的控制器单独的js文件,这样的模式将是以下几点:
//let's say you need to use controller User:
var controller = ControllerManager.get('User');//I believe you have some controller manager, similar to Sencha's Ext.ControllerManager
if(controller){
//use it here
}
else {
loadScript([url of your controller script], controllerLoaded);
}
...
function controllerLoaded(){
//create controller instance here if needed and use it then
}
...
function loadScript(url, callback){
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
UPDATE 为了新的控制器整合到已经运行Ext.app.Application
您需要扩展Ext.app.Application
并添加以下方法:
addController: function(name){
//at this point your controller .js file should be already loaded into the DOM
var c = this.getController(name); //controller will be created automatically by name in this getter
//perform the same initialization steps as it would have during normal ExtJs process
c.init(this);
с.onLaunch(this);
}
顺便说一句,而不是使用自定义的方法来加载javascript文件动态,你可以使用ExtJS的的Ext.Loader
内置方法:
/**
* Load a script file, supports both asynchronous and synchronous approaches
*
* @param {String} url
* @param {Function} onLoad
* @param {Object} scope
* @param {Boolean} synchronous
* @private
*/
loadScriptFile: function(url, onLoad, onError, scope, synchronous)
控制器通常包含业务逻辑,所以你要如何生成,如果你的业务逻辑一般方式控制器是特定于您的应用程序?或者你想为你的模型生成刚才的CRUD操作?如果是这样,你可以考虑创建通用控制器,它将与不同类型的模型一起工作。但是如果你的控制器不同,那么(如果我理解你正确),你需要通过AJAX调用从服务器加载这些控制器,对吧?请澄清。 –
是的,我需要通过AJAX调用从服务器加载这些控制器,并不是所有的一次 – jonny