在我的qooxdoo應用程序中,我有4個按鈕。登錄,註銷,註冊和配置文件。每個按鈕都有一個動作類。這些類是從一個共同的抽象類中分類的。通過使用命令模式,每次單擊按鈕時,我都會調用相關類的execute函數。該功能看起來像這樣如何從此功能減少樣板?
execute: function() {
var contentString = "login-form";
//do some generic stuff
if (win.getContentString() === contentString) {
//do some generic stuff
} else {
var content = new myapp.apps.userActions.SLoginForm();
//do some more generic stuff
}
}
即執行功能在所有4子類和改變的唯一的東西得以實施是變量的內容和contentString。
我在考慮使用工廠函數,並且每次都根據contentString變量返回適當的對象。
execute:function(){
var contentString = "login-form";
this.doTheGenericStuff(contentString);
},
doTheGenericStuff: function(contentString){
//do the generic stuff
var content = this.getTheObject(contentString);
//do some more generic stuff
},
getTheObject: function(contentString){
switch(contentString){
case "login-form":
return new myapp.apps.userActions.SLoginForm();
break;
case "register-form":
return new myapp.apps.userActions.SRegisterForm();
break;
//etc
}
}
雖然這似乎確定(沒有測試它尚未)我不喜歡它多,因爲我每次添加新的行動時間,我必須更新工廠函數。有沒有更聰明的方法來實現這一目標?也許我不知道的JavaScript的一些功能?