2012-12-31 53 views
0

我有一個ExtJS類,看起來像這樣:通話功能動態

Ext.define("RuleExecutor", { 
    singleton: true, 
    displayMessage: function(msg) { 
     Ext.Msg.alert('Popup Message', msg[0]); 
    }, 
    disableById: function(field) { 
     Ext.getCmp(field).setDisabled(true); 
    }, 
    //more functions are here... 
}); 

現在我得到一個字符串=>str其中包含我需要運行的方法名。我需要調用由字符串指定在RuleExecutor 方法str中

的方法被稱爲正確,但參數不通過。

像這樣:

//arguments is an array 
function RunRule(str, arguments) { 
    //I tried this.... 
    var fn = RuleExecutor[str]; 
    fn(arguments) 

    //This doesn't work either.. 
    RuleExecutor[str].apply(this, arguments); 
} 
+0

這是一個單身,所以RuleExecutor.displayMessage( '布拉布拉')應該工作?或者我錯過了什麼? – asgoth

+0

你在哪裏調用'RunRule()'?我不知道ExtJs是否適用於其他內容,但按照慣例,函數名稱以小寫字母開頭。 – 11684

+1

現在我看到'方法被正確調用...'。抱歉! – 11684

回答

1

這是你在找什麼?

Ext.onReady(function() { 
    Ext.define("RuleExecutor", { 
     singleton: true, 
     displayMessage: function (msg) { 
      Ext.Msg.alert('Popup Message', msg[0]); 
     }, 
     disableById: function (field) { 
      Ext.getCmp(field).setDisabled(true); 
     } 
    }); 

    var str = 'displayMessage'; 
    RuleExecutor[str](['bar']); 
}); 
2

不要使用'arguments'作爲變量名稱。在JavaScript中已經有一個名爲'arguments'的內置類似數組的對象。你的方法可能是這樣的:

function RunRule(str) { 
    var slice = Array.prototype.slice, 
     args = slice.call(arguments, 1); 
    RuleExecutor[str].apply(RuleExecutor, args); 
} 

我從「真正的」數組原型使用的slice方法。行:

args = slice.call(arguments, 1) 

拷貝所有參數除了第一個到args變量。你叫RunRule這樣的:

RunRule("displayMessage", "Hello");