Debugging JS/CoffeeScript code: Events, Callbacks etc - javascript

Recently I am finding difficulty understanding whats happening in a CoffeeScript/Backbone app. Its hard to trace whats happening quickly without a very slow step through. The problem I think is: I know an event is triggered (Backbone view event). But I dont know which functions are called because of it. There maybe more than 1. I may not even know with view partial is the event defined (so I cant put a breakpoint?)
Is there a debugger which plots the execution of the program as a graph? So that I can zoom into what I need, or maybe something I can use to "visualize" the execution of my code. Maybe not, if what should I be looking out for. I am not sure where I need to put a breakpoint since I dont know where some events are triggered. Then sometimes I find it hard to understand why the code step through might be jumping here and there, maybe its multiple events and their handlers executing?

Everything in Backbone (Views, Models, Collections, Routers) extends Backbone.Events. That means they have an _events property that contains each bound event (e.g. change) with an array of their subscribers.
In order to access this open your javascript console in chrome, firefox or safari (or anything but IE) and enter the name of a globally accessible instantiated object with ._events at the end. E.g.
products._events
After pressing enter you should be able to expand this and see what is published and subscribed.

Related

How to find the place where a certain function is called?

I'm writing a webpage, where I need to do some little changes. The problem is, I need to find the place, where one certain function is called (there are plenty of JavaScript files, so I'm not able to go through them line by line). Do you have any idea, how could I find it out?
I know how to do step-by-step debugging in Firebug or similar browser consoles, but still, I don't know how to recognize the place where the function was called.
I prefer working with consoles in Firefox or Chrome.
Debugging Tips For Chrome:
There are probably a number of ways you can find out where a change is coming from. But I find this one a time saver when it comes to tracking down changes in the DOM. (which will usually lead me to a function I am looking for)
Break on subtree modification or attribute modifications. To do this right click on an element in the DOM tree. Specifically the one you think the change is being applied to. From there you will get a context menu which will give you these options. Selecting either one with set a DOM breakpoint.
If this triggers the debugger you can then proceed to step through the code by using F11 and shift + F11 to skip over functions (useful if you wind up in a library like jQuery). While doing this, pay attention to the call stack. This will tell you where the code is coming from..
More in depth information:
https://developer.chrome.com/devtools/docs/javascript-debugging
To get to know the caller of a function just set a breakpoint at the first line of it. Once the breakpoint gets hit, you can see within the stack trace from where it was called.
Firefox DevTools
Firebug
Chrome DevTools
If you have access to the scripts, you could add at the end of every function you want to watch :
console.trace()
This will output in Chrome's console what function have been called with its position in the file (line number)

How do I find what Javascript is running on certain events?

I'll pick Chrome for this example, but I'm open to a solution from any browser.
Use Case:
I have an update button on my website that is used to update item quantities in a shopping cart. I'd like to allow a user to enter a 0 and click update in order to remove the item. Trouble is, there is some listener in some js function that is denying the ability to enter a 0 and click update (after clicking update the old quantity remains).
My question is, what developer tool can I use to find which js function is running during that event? I don't think that Chrome's inspector does this, and I'm not very familiar with Firebug, but I couldn't find the functionality there either.
I feel that I should be able to inspect js firings just like I do css stylings. Is anyone aware of a tool I may use?
I've had to debug some particularly nasty unseen-cause Javascript issues at my job. Knowing the full depth of developer tools like Chrome's is definitely helpful. It undeniably takes some creativity to find places that might be causing the issue, but a few tips:
Tracking down event listeners
Under Chrome's Elements view, try Inspect-ing an element (right-click, Inspect); then, on the right side of the developer view, scroll down to Event Listeners. Here you can view what code files have hooked up an event. Often, this will just point you to a middle-framework from the really devious code you're looking for, but sometimes it will point you in the right direction.
Trapping a DOM modification
Many of the unwanted effects I see are because of something changing some value or attribute on the page that I don't want. Anytime this happens, you can right-click on the element (under the Elements view) and say "Break on..." and the specific scenario you're looking for. When Chrome then hits a breakpoint, you can then look downward in the Stack Trace until you find something recognizable that shouldn't be called.
EDIT after reaching ten votes!
Trapping a JS object modification
If the change you're interested in is code-internal, not in the UI, things get trickier. What's meant by this scenario is that you know somewhere in the code, something incredibly annoying like the following is happening.
company.data.myObject.parameter = undefined;
In this situation, you know myObject is still the same object, but it's being modified, perhaps unintentionally. For that, I often insert the following bit of code, sometimes just through the developer console at some point before said modification happens.
Object.defineProperty(company.data.myObject, 'parameter', {
set: (val) => {
debugger;
}
});
This includes an arrow function - you're only using this for debugging and Chrome supports it, so might as well save keystrokes. What this will do is freeze your debugger as soon as some line of code attempts to modify myObject's "parameter" property. You don't necessarily have to have a global reference to the variable if you can run this line of code from a previous breakpoint that will have the given object in the locals.
Otherwise, if all I'm starting out with is the HTML code, and I want to tie that to Javascript code, I'll often just look for identifying features like "id" elements, and search all JS files in my development directory for it. Normally, I can reach it pretty fast.
Open your page in Firefox with Firebug enabled.
Go to console tab in firebug and click profiling
enter 0 in the textbox and click the button.
Stop profiling.
You will be able to see all the javascript functions which have executed due to your actions. You can view them one by one to figure out which method has caused the mischief.
Go to you code. If you are using jQuery there is going to be a function that will be called with the class or id of that particular update button. Or, if you are using Javascript, there is going to be a function called inside the
<input type="button" name="update" onclick="update()">
These are the two ways to look for the function that is being called; there is no software that I know
Download Firebug for Mozilla Firefox, open it, click on Net and refresh your website. Than, you can see which files are loaded on the page.
If you want to check on errors and what goes wrong with an explanation, than click on console and refresh the page once again. You will see the errors and on which line it goes wrong.
Note: in your console, you can say hold or stop, so that the js file stops loading. And you can edit the script by clicking on script in Firebug. Debugging is simple, as it says on their official page https://getfirebug.com/javascript

DOM MutationObservers: How to support this one important use of DOM3 Mutation Events?

I get wordy sometimes: tl;dr: read the bold text.
The motivation behind deprecating Mutation Events is well understood; their efficacy in achieving many types of tasks is questionable.
However, today, I have discovered a use for them that is highly dependent on those very same undesired properties.
I will first present the question, and then present the reasons that lead me to the question, because the question will be absurd without it.
Is it possible to use the new Mutation Observers in a way that we can have the VM stop at the instant of the change (like the DOM3 Mutation Events do), rather than report it to me after the fact?
Basically, the very thing that makes the Mutation Observer performant and "reasonable" is its asynchronicity, which means (necessarily, it seems) throwing away the stack, pushing a record mutation to a list, and delivering the list to qualified Observers at the next tick or several ticks later.
What I am after is precisely that stack trace of the DOM3 Mutation Event. I really really hope this will work, but basically the Mutation Event callback (which I am allowed to write) will have a stacktrace that will lead me back to the actual code that created my element I'm listening for. So in theory I'd write a Mutation Event handler like this:
// NOT in an onload cb
$("div#haystack").on('DOMNodeInserted', function(evt) {
if (is_needle(evt.target)) {
report(new Error().stack); // please, Chrome, tell me what code created the needle
}
});
This gives me the golden answer.
It seems that Mutation Observers will make it impossible to extract this information. What, then, am I to do once Mutation Events are completely taken out? They have been deprecated for a while now.
Now, to explain a little better the real actual circumstances, and why this matters.
I have been trying to kill a bug which I describe here: I have built a full-DOM serializer which nicely spits back out every element that exists on the webpage, and in comparing them, the broken page and the working page are identical. I have tested this and it is pretty nice. it captures every little thing that's different: Whatever hovery-thing my mouse happens to be over, the CSS class that gets consequently set will be reflected in the HTML dump. Any text of any form on the page will show up if you search it (provided it doesn't span across elements). All inline JS (and more importantly, all differences between inline JS) is present.
I have then gone on to verify that the broken page is missing several event handlers. So none of the clickable items respond to hover or clicks, and therefore no useful work can be done on the interactive form. This is not known to be the only problem, but it does fully explain the behavior. Given that the DOM has no differences in inline JS that explains the difference in behavior, then it must be the case that either the content of the linked resources or the invisible properties of elements (event handlers being in this category) are causing the difference in behavior.
Now I know which elements are supposed to have handlers, but I know not where in the comically large code base (ballpark: 200K lines of JS all loaded as one resource, assembled by several M lines of Perl serverside code) lies the code that assigns the events.
I have tried JS methods to watch modifications of object properties, such as this one (there are many, but all work on the same principle of setting setters and getters), which works the first time, and then subsequently breaks the app afterward. Apparently assigning setters and getters cause the system to stop functioning. It's not clear to me how I can take that approach of watching property assignments to a point where i can get a list of code points that hit a specific element. It might be feasible, but surely not if I can only fire it once, and it breaks everything thereafter.
So watching variables with JS is out.
I might be able to manually instrument jQuery itself, so that when my is_needle() succeeds on the element processed by jQuery, I log all event-related functions performed by jQuery on that element. This is dreadful, and I will resort to this if my Mutation Observer approach fails.
There are yet more ways to skin the cat of course. I could use the handy getEventListeners() on my target element when it is working to get the list of event listener functions that are on it, and then look at the code there, and search the code base to find those functions, and then analyze the code to find out all the places there those functions are inserted into event handlers. That is actually pretty straightforward.
Now I know which elements are supposed to have handlers, but I know not where in the comically large code base (ballpark: 200K lines of JS all loaded as one resource, assembled by several M lines of Perl serverside code) lies the code that assigns the events.
Have you considered simply instrumenting .addEventListener function calls one way or another, e.g. via debugger breakpoints or by modifying the DOM element prototype to replace it with a wrapper method? This would be browser-specific but should be sufficient for your debugging needs.
You also might want to try firefox's tracer, available in nightlies I think. It basically records function execution without the need to use breakpoints or instrumenting code.

All events in Backbone app fire twice. Occurs randomly

First, some background. I'm fairly certain this is not because of zombie views. I use requireJS and I have only one instance of main views at any given time.
Also, this behavior is random, I haven't been able to reproduce it even once, but several of my users have pointed it out and shown me a video where every click on the app seems to trigger the handler twice. The clicks happen very very fast. It can't be mechanical failure of the mouse because the problem has been reported on multiple machines. The reports are from people with fast Internet connections, for what it's worth.
Is it possible that two instances of the app are running at the same time? Are there any steps I can take to isolate a problem of this kind in backbone?
Apologies for the wall of text, please let me know if I can put up any extra information or relevant pieces of source.
Edit : I've managed to recreate this in Opera. After stepping through part of the code that fires twice (I was inspecting code that opens a modal), I was able to look at the view that triggers the event. Both views have the same CID, so this cannot be attributed to Zombie views right?
In my experience, this is almost always related to zombie views, or other DOM leaks. My best friend in this case if the Web Inspector Profiles -> Take Heap Snapshot and look for detached DOM tree (type "detached" in the search field).
It can occur in tricky cases, even if you think you're only instanciating views once.
Beyond that, you'll have to show us some code ;)
The problem here was that I was running a third party library that reports JS errors. Due to a n error on their part, event bindings on page were affected and this caused the confusion inside the application.
Moral of the story - Whenever you hit an error you feel is impossible, remove your third party dependencies one by one and confirm the problem is your fault to begin with.

Non-breaking breakpoints (trace points) in Javascript?

This is a rather complicated question that may simply be impossible with what's currently available, but if there was an easy way of doing it it would be huge.
I'm debugging some JavaScript in Chrome, and because it's very event-driven, I prefer to get trace reports of the code (what got called, etc.) instead of breakpoints. So wherever I leave a breakpoint, I'd like to see the local function name and arguments.
The closest I can get is to drop a conditional breakpoint in, like the following:
There are two big problems with this approach:
Pasting this into each breakpoint is too cumbersome. People would be far more likely to use it if it could be chosen as the default action for each breakpoint.
In Google Chrome, the log calls get fired twice.
Any ideas on a way to surmount either of these problems? I think it might be possible in IE with VS, but the UI there seems equally cumbersome.
IE11 now has "tracepoints", independent of Visual Studio. They do exactly what you asked for three years ago. I don't see them in Chrome or any other browsers yet, but hopefully they will catch on soon!
The best option I found was to edit the javascript code in Chrome's Javascript panel, adding a console.log.
It would only work after the page has been loaded (unless you can afford to put a break point after refresh and then add the logging lines) and (to be worse) you would have to do it each time you reload the page.
Good luck with your search!
I couldn't find something to do this, so I wrote my own.
Now, instead of constantly inserting and removing console.log calls, I leave the logging in and only watch it when necessary.
Warning: specific code below is untested.
var debug = TraceJS.GetLogger("debug", "mousemove");
$('div').mousemove(function(evt) {
debug(this.id, evt);
});
Every time the mouse is moved over a DIV, it generates a logevent tagged ["mousemove", {id of that element}]
The fun part is being able to selectively watch events. When you want to only see mousemove events for element #a, call the following in the console:
TraceJS('a');
When I want to see all mousemove events, you can call:
TraceJS('mousemove');
Only events that match your filter are shown. If you call TraceJS(no argument), the log calls stop being shown.

Categories

Resources