2012-07-04 56 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试过了,它的工作原理,谢谢! –

相关问题