Search code examples
javascriptcontrollerextjs4

EXTJS assign function to variable and call it dynamically


In my controller, I have the following ref and one function that I call after clicking a button. Is it possible to construct a ref method and then call it? I just want in a single function to handle many cases and I want to avoid if statements (as it is required in the project. It is supposed to be generic)

The type will come as a parameter to the function.

     refs    : [{
        ref      : 'saleForm',
        selector : 'sale saleform'
     }],

         init: function () {    
            this.control({
                     'salesview #mybutton':{
                     click : this.onSaleClick 
                    }
            }); 
         },

    onSaleClick : function(){

       //this.getSaleForm().show();//works

       var type = "Sale";   
       var method = "get"+type+"Form()";    
       this.window = window;
       this.window[method]().show();        
   }

Solution

  • This should be possible without problems. Try something like this :

         init: function () {    
            this.control({
                'salesview #mybutton':{
                    click : function(){
                        this.onGenericClick("Sale")
                    }
                 },
                 scope: this
            }); 
         },
    
    onGenericClick : function(type){
       var method = "get"+type+"Form()";    
       this.window = window;
       this.window[method]().show();        
    }
    

    You must define the scope of the listener to be able to refer to this. Here's the doc about the listener object. Instead of passing the scope globally in this.control, you could pass it just for one event, like this:

    this.control({
        'salesview #mybutton':{
            click: {
                fn: function(){
                    this.onGenericClick("Sale")
                }, 
                scope: this
            }
         }
    });