简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM