Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Lazy Binding for Logging in JavaScript

5.00/5 (2 votes)
29 Jan 2015CPOL 10.8K  
How to wrap costly functions to execute them only when needed, especially for debugging purposes

Introduction

If you are still using alert() function to debug your JavaScript program, it's time to move on to using console.log() function so that log messages are only visible in Developer Tool.

Next, you need to know that the following line has a huge negative impact on your script's performance:

JavaScript
console.log( $('#div1').html() ); 

Why? Because the div1 could be a huge element on the page. So, you Googled and learned to create a Logger module which would suppress certain messages by a pre-configured log level, similar to:

JavaScript
Logger.debug("I'm a debug message!");
Logger.info("OMG! Check this window out!", window);
Logger.warn("Purple Alert! Purple Alert!");
Logger.error("HOLY SHI... no carrier.");

Source: https://github.com/duongchienthang/js-logger

With the new Logger module, you may think it would take away the cost of reading the DOM by doing:

JavaScript
Logger.setLevel(Logger.OFF);
Logger.debug( $('#div1').html() ); 

But you are wrong. The beast $('#div1').html() still runs as always and costs you performance unless you do the following:

JavaScript
Logger.debug( $().html.bind($('#div1')) );

I know it hurts your eyes if you are not familiar with the Function.prototype.bind() function. The $().html.bind() piece will return a wrapper function of the jQuery .html() function. That wrapper function will always be evaluated instead of the actual .html() function.

You can apply this trick to any functions that would potentially consume lots of memory and processing time, such as:

JavaScript
Logger.debug( JSON.stringify.bind(null, myVeryBigAndRecursiveJsObject) );

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)