n01dea
n01dea

Reputation: 1580

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

Upvotes: 1

Views: 380

Answers (2)

ygoe
ygoe

Reputation: 20374

For those who are also looking for this, like I just did, there's a solution in Chrome only. For debugging it might be enough.

Source: https://devtoolstips.org/tips/en/capture-node-creation-stacks/

Essentially, in Chrome's DevTools, you can enable the experiment "Capture node creation stacks". After enabling it and reloading DevTools as suggested, you can select the suspicious node in the DevTools and see its creation stack trace just like its styles, layout etc. in a separate tab on the right side.

Upvotes: 0

Gideon Pyzer
Gideon Pyzer

Reputation: 24008

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.

Upvotes: 1

Related Questions