0

Consider the following html code:

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div id="callerA">A Caller</div>
<div id="callerB">B Caller</div>
<style> 
    #callerA,
    #callerB {
        height: 20px;
        width: 200px;
        background-color:red;
    }
</style>
<script type='text/javascript'>
    function callerA() {
        setListener(jQuery("#callerA"));
    }

    function callerB() {
        setListener(jQuery("#callerB"));
    }

    function setListener($elem) {
        $elem.on('click', function() {
            console.trace();
            alert("elem was clicked");
        });
    }

    callerA();
    callerB();
</script>

NOTE: I didn't put this in a JSFiddle, or JSBin because console.trace() is not working on them

At the moment, if I click on the callerA div or the callerB div, the click event with the alert and the trace fires for both. But when I am inspecting the console, the console.trace() method, can only trace back my call to this point:

(anonymous) @   trace.html:23
dispatch    @   jquery-3.1.0.js:5110
elemData.handle @   jquery-3.1.0.js:4918

Is there any way that I could get the call stack even further? What I would like to see is something like this, depending on which element I clicked on:

(anonymous) @   trace.html:23
dispatch    @   jquery-3.1.0.js:5110
elemData.handle @   jquery-3.1.0.js:4918
setListener @ trace.html:22
callerB @ trace.html:18

I am well aware that my actual function only fires when I click on the element, and that is considered the entry place for the stack, but isn't there some kind of "hack" or some easy to implement way, to trace the call back even further?

Adam Baranyai
  • 3,635
  • 3
  • 29
  • 68
  • I don't think so, because the trace you're seeing is the one of the click callback, not the one of the binding. You need to keep track of that info (if you want to) when you assign it, otherwise the trace is just working as intended. – briosheje Jul 24 '20 at 09:51
  • is there any way to store the trace in a variable when I am assigning the listener? – Adam Baranyai Jul 24 '20 at 09:52
  • 2
    yes, but it's going to be slighly more complex than the (possible) benefits you can get out of it due to the fact that different browsers implements the trace differently, I think you can find some relevant informations about that here: https://stackoverflow.com/questions/6715571/how-to-get-result-of-console-trace-as-string-in-javascript-with-chrome-or-fire – briosheje Jul 24 '20 at 09:55

0 Answers0