A couple of days ago, I started implementing a rather interesting piece of code. It was late into the night, and I was not feeling like doing my regular work and neither was I sleepy.
Second consecutive blog post relating to adding something dynamically to an already rendered Html component, while the previous one was for adding buttons dynamically to jQuery UI dialogs here, this one is for adding tools dynamically to ExtJs Panels.
As you might be knowing, tools are small icon-only buttons rendered towards the right of an ExtJs Panel title that come in handly for executing custom operations (similar to Minimize/Maximize/Close buttons in a regular Desktop window, you can specify any number of tools for your panel, and you can control the action executed when a tool is clicked).
Well according to ExtJs docs, tools can only be specified in the config options for the Panel, but cannot be added dynamically. But I needed to add the tool dynamically to the Panel, as the Panel was already instantized and shown from another portion of the application code, that I did not want to be modified.
One option could be to add the tool to config options itself with its visibility as hidden and then show it as required. But as I said, I needed to add it dynamically to a rendered Panel because the code which actually instantized the Panel existed in another portion of the application that was frozen.
ExtJs docs do not specify a method available for this purpose, but having a look at ExtJs Panel class' source code, I spotted the addTool method (which has been marked as private in the Panel class), and observed that tools specified in the config options for the Panel also get added one-by-one by repeated calls to this method.
A quick look at the method code made me believe that this method can be safely called after the Panel has been rendered and would behave as expected by adding the tool at the end of the already rendered list of tools.
Upon testing, it worked as expected and I wondered why this method has been marked as private when it can be used conveniently at run-time to manipulate tools for a Panel.
The example below would allow you to perform all manipulations for a Panel tool (including adding, removing, showing and hiding tools):
The source for the example is attached below.
Notice we can only add a tool at the end of the current tools list with this method. If you want to insert it somewhere in between the existing tools, you can either create a new method let's say insertTool and use the code of the addTool method as guidance to insert dom for the new tool at an appopriate position or use addTool itself to add the tool at the end and afterwards manipulate the tool's dom to move it at an appropriate position (Ext.DomHelper should come in handly for both options).