3

My script sends text to the console output from several places in Javascript (see examples), how do I bind an event handler function to the log function itself so that a function is executed each time the event is triggered?

try {
    //some code
} catch(e) {
    console.log("error: "+e)
}

function x(n) {
    //some code
    console.log(str)
}
2
  • 1
    Write an event binding and have console.log("Some message"); in the function? Commented Dec 21, 2013 at 21:15
  • Redefine the log function to trigger an event you can bind a handler to. Commented Dec 21, 2013 at 21:18

1 Answer 1

11

I would override console.log (but store it in a different variable, in case we want to use it) like so:

var nativeLog = console.log.bind(console) //store native function

console.log = function(text){ //override
    nativeLog("<<<" + text)
}

Abbreviating console.log in JavaScript

Sign up to request clarification or add additional context in comments.

4 Comments

You can create a new event that gets trigger from the overridden console.log, e.g. jsfiddle.net/SzE34
@towr - that would be an illegal invocation of the function you're currently overwriting.
@adeneo I don't quite understand what you mean, though I figure it has to do with the (probably better) way TastySpaceApple stores the native function? My intent was more to add an event to the mix, though. --- Firefox didn't complain, but if you can give me some pointers to better my javascript I'd appreciate it.
@towr - chrome does throw an "illegal invocation" error, and using bind() would be better, otherwise the example of creating an event and triggering it is spot on, and surely the way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.