How to switch console.log to jQuery widget?

I have been working on some jQuery widgets for work / fun lately ( github ), and there is something else that bothers me.

When I use the widget in my application, I want to be able to pass a debugging parameter that will enable or disable logging (using console.log) completely only in this plugin.


The best decision:

from:

(function( $, undefined ) {

})(jQuery);

to:

(function( $, console, undefined ) {

    if (!o.debug) console = { log: function(){} };

})(jQuery, console);

One problem left

If I load two widgets like:

$myDiv.myWidget({debug: true});
$myDiv2.myWidget({debug: false});

I will not have later debugging from the 1st instance. Any ideas?


[original] So far, I have used a piece of code that I found on the Internet:

var logger = function() {
    var oldConsoleLog = null;
    var pub = {};

    pub.enableLogger = function enableLogger() {
        if(oldConsoleLog == null) return;
        window['console']['log'] = oldConsoleLog;
    };

    pub.disableLogger = function disableLogger() {
        oldConsoleLog = console.log;
        window['console']['log'] = function() {};
    };

    return pub;
}();

Then on _create()I can do this:

if (!o.debug) {
        logger.disableLogger();
}

It looked good, but it is not a plugin, as it will disable console.log for my entire application.

, .log( console.log, , /, ).

!

+3
3

, , - . .

(function(console){
  if (!o.debug) console = { log: function(){} };

  // Rest of your code goes here
})(console);
+3

, . , . 1) 2) console.log

- , true, false . , ( )

if. , . , debug. debug, , console.log .

+1

I never used parentheses to access attributes window, but it looks like this can do the job. Although note that if you disableLogger()call twice without a call in enableLogger()between, you will not be able to re-enable logging.

0
source

Source: https://habr.com/ru/post/1786470/


All Articles