Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set up JavaScript to call function with different parameters

I have the following ExtJS controller code:

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

and the following event handlers:

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');
},

Problem: the current code is redundant: handlerA and handlerB just call commonFunc with different parameters

Question: I would like to remove handlerA and handlerB and instead call or apply the common function commonFunc with the arbitrary parameters within handlerA and handlerB functions above, for different event handlers. Is it possible?

Example:

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

Many thanks!

like image 892
Joseph Victor Zammit Avatar asked May 25 '26 13:05

Joseph Victor Zammit


1 Answers

how about this:

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');
            }
        }
    });
},
like image 69
red-X Avatar answered May 28 '26 03:05

red-X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!