Skip to content

Commit

Permalink
Merge pull request #57 from cederberg/refactor_bind_method
Browse files Browse the repository at this point in the history
Refactored to use more generic bindMethod() function.
  • Loading branch information
pimterry committed Oct 12, 2014
2 parents 127e5a4 + 466ab91 commit 6d6ffd7
Showing 1 changed file with 14 additions and 22 deletions.
36 changes: 14 additions & 22 deletions lib/loglevel.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,38 +21,30 @@
if (typeof console === undefinedType) {
return false; // We can't build a real method without a console to log to
} else if (typeof console[methodName] === "function") {
return boundToConsole(console, methodName);
return bindMethod(console, methodName);
} else if (typeof console.log === "function") {
return boundToConsole(console, 'log');
return bindMethod(console, 'log');
} else {
return noop;
}
}

function boundToConsole(console, methodName) {
var method = console[methodName];
if (method.bind === undefined) {
if (Function.prototype.bind === undefined) {
return functionBindingWrapper(method, console);
} else {
try {
return Function.prototype.bind.call(console[methodName], console);
} catch (e) {
// In IE8 + Modernizr, the bind shim will reject the above, so we fall back to wrapping
return functionBindingWrapper(method, console);
}
}
function bindMethod(obj, methodName) {
var method = obj[methodName];
if (typeof method.bind === 'function') {
return method.bind(obj);
} else {
return console[methodName].bind(console);
try {
return Function.prototype.bind.call(method, obj);
} catch (e) {
// Missing bind shim or IE8 + Modernizr, fallback to wrapping
return function() {
return method.apply(obj, arguments);
};
}
}
}

function functionBindingWrapper(f, context) {
return function() {
Function.prototype.apply.apply(f, [context, arguments]);
};
}

function enableLoggingWhenConsoleArrives(methodName, level) {
return function () {
if (typeof console !== undefinedType) {
Expand Down

0 comments on commit 6d6ffd7

Please sign in to comment.