javascripthtmldebugginggoogle-chrome-devtoolssapui5

How to Trace JavaScript Dynamically Created Elements to Their Origins in Code?


Have a SAPUI5 application. Html view created by xml. JavaScript controllers. Some elements of this application, e.g. buttons are created somewhere dynamically within the controllers of the respective views. I.e. cannot use the id of an element to get it in the controller because the ids are dynamically created. Would like to get those dynamically created elements of the application to modify them, e.g. modify the buttons. What's the best way to trace a dynamically created element back to its code where it's created? E.g. how to trace a button back to it's origin in the JavaScript controller? It's a huge application and a view has multiple controller. I'm not just lazy.

enter image description here


Solution

  • The render function in the component's renderer class is what (eventually) creates the DOM element. You can inject a debugger statement into it like so:

    let __buttonRender = sap.m.ButtonRenderer.render;
    
    sap.m.ButtonRenderer.render = function() {
        let control = arguments[1];
        console.log('Creating button: ', control.sId);
        debugger;
        return __buttonRender.apply(this, arguments);
    }
    

    You can probably modify the control object based on the Id here. I'm not exactly sure what your end goal is here. The renderer is probably taking attributes and data from XML, so if you want to modify the buttons, I'd do it at the data source. The above could would allow you to hack the model before it reaches the DOM, but it's kinda nasty.