开发者

How to toggle console.log in a jQuery widget?

开发者 https://www.devze.com 2023-02-05 07:51 出处:网络
I\'ve been working on some jQuery widget for work/fun lately (github) and there is still something that is bothering me.

I've been working on some jQuery widget for work/fun lately (github) and there is still something that is bothering me.

When i use a widget in my app, i want to be able to pass a debug option, that will enable or disable logging (using console.log) entirely only in this plugin.


best solution so far :

from :

(function( $, undefined ) {

})(jQuery);

to :

(function( $, console, undefined ) {

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

})(jQuery, console);

There is one problem left

If i load two widgets like :

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

I won't have later debug from 1st instantiation. Any ideas ?


[original] So far i've used a piece of code i've 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 sth like :

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

Looked quite good however, it is not plugin specific, as it will disable console.log for my entire app.

One important point is that i want to be able to keep console.log line logging feature (no wrapping of console.log since as far as i know / tried, it will replace logging line info with useless wrapped call line).

Thank you !


The easiest option I can think of is to override console inside your scope. Like this.

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

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


I find that architecture odd. It seems to me that there are two ways to solve this. 1) Create a debug plugin, or 2) have your plugin call console.log

In the first case - I would always instantiate the debug plugin, either with true or false as the debug option. And I would always have my other plugin call the logging function (if that logging function exists)

In both cases I would not litter the code with if statements. I would have my other plugin have its own log call. In the first case it would check if the debug plugin exists. In the second case it would check it's own debug option to see if it should console.log or not.


I've never really used brackets to access attributes of the window, but that looks like it might do the job. Though note if you call disableLogger() twice without calling enableLogger() in between, you will not be able to re-enable logging.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号