2012-07-04 60 views
3

我有以下ExtJS的控制器代碼:設置JavaScript來調用函數使用不同的參數

init: function() { 
    this.control({ 
     '#menuitem-A': { click: this.handlerA }, 
     '#menuitem-B': { click: this.handlerB }, 
    }); 
}, 

和下面的事件處理程序:

commonFunc: function(param1, param2) { 
    // do something with param1 and param2 in here 
}, 

handlerA: function(button, event) { 
    this.commonFunc('param-A1', 'param-A2'); 
}, 

handlerB: function(button, event) { 
    this.commonFunc('param-B1', 'param-B2'); 
}, 

問題:當前代碼是冗餘的: handlerAhandlerB只需撥打commonFunc不同的參數

問題: 我想內handlerAhandlerB功能與任意參數以除去handlerAhandlerB和代替callapply公共功能commonFunc以上,對於不同的事件處理程序。可能嗎?

例子:

init: function() { 
    this.control({ 
     '#menuitem-A': { click: /*commonFunc with ['param-A1', 'param-A2']*/ }, 
     '#menuitem-B': { click: /*commonFunc with ['param-B1', 'param-B2']*/ }, 
    }); 
}, 

非常感謝!

回答

5

這個怎麼樣:

init: function() { 
    this.control({ 
     '#menuitem-A': { 
      click: function(button, event){ 
       this.commonFunc('param-A1', 'param-A2'); 
      } 
     }, 
     '#menuitem-B': { 
      click: function(button, event){ 
       this.commonFunc('param-B1', 'param-B2'); 
      } 
     } 
    }); 
}, 
+0

因此,它是不可能建立的函數(當事件觸發),而無需實際建立一箇中間函數的調用? –

+1

你可以使用Ext.Function.bind(),但它本質上只是做同樣事情的捷徑。上面提供的答案在功能上與您的答案沒有區別。 –

+0

@EvanTrimboli試過了,它的工作原理,謝謝! –

相關問題