Tutorial :Javascript Overriding issue



Question:

I struck up in a Javascript method overriding problem for a while. the problem is i got onclick event handler on one of my controls and i need to to do inject some method before the event handler triggers the actual method.

assume DGrid.Headerclik is actuall assigned to onclick event.

And this is what i did

  DGrid.Headerclik  = handleinLocal;  

so whenever user clicks the grid now the control comes to handleinLocal method. here i have to do some processing and then call the base Headerclik().

  function handleinLocal(){        // here i need to call the DGrid.Headerclik() method (base)    }  

but this is not working as expected. on calling the DGrid.Headerclik() within the handleinLocal() recursively calls the handleinLocal() method. But i need to call the base method...

is there a way to achieve theis in JavaScript??


Solution:1

You should store the previous handler in a (closure) variable:

(function() {     var oldHandler = DGrid.Headerclik;       DGrid.Headerclik = handleInLocal;       function handleInLocal() {        // ...        oldHandler();        // ...     }  })();  


Solution:2

Save the original callback in a variable before you reassign it your own handler. Then after you have done what you need to do, invoke the original handler from the variable.

var callback = DGrid.Headerclik;  DGrid.Headerclik = handleinLocal;    function handleinLocal()  {       ...your code...       callback();  // invoke original handler  }  


Solution:3

Copy the original click event handler to a variable then in your new click event handler, call the original click handler

var oldOnClick = DGrid.Headerclik || function() {};    DGrid.Headerclik = handleinLocal;    function handleinLocal() {     // Do what you need to do     oldOnClick();           }  


Solution:4

Thanks guys (all) for your reply.. your method is elegant.. this successfully calls the base method, i forgot tell u one morething, DGrid is a sepearate function got its own methods & properties. And i got one more problem here..

DGrid.Headerclik() iself uses 'this' operator to access the methods & properties from its scope.. so on calling the oldHandler() it runs within my local. not exactly in the DGrid scope. (this operator only returns the properies of my page not in the DGrid )

to avoid this i assigned the oldHandler back to the DGrid.Headerclik and calls DGrid.Headerclik () directly..

var oldHandler = DGrid.Headerclik;     DGrid.Headerclik = handleInLocal;  function handleInLocal(sColumnIdx){      FormColumnWidthJSONArray();      //OldHandler(sColumnIdx)           DGrid.Headerclik= OldSCCHandler;      DGrid.Headerclik(sColumnIdx) // To Call the actual Column Click handler in DGrid;      DGrid.Headerclik= HandleLocal;  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »