Wednesday, July 04, 2007

Handy "Alert Debugging" tool

One of the coolest things about OO Javascript is that methods can be written to as if they are variables. This means that you can re-write functions on the fly. Bad for writing maintainable code if you're not structured; Fantastic for things like MVC controllers (rather use the controller to forward calls on to the model, you use it to rewire the view so that it calls it directly, and all without the view even realising it!). What I didn't realise was that the standard window object (and probably so many others out there) can have its methods overwritten like any other. Probably the simplest example of that proves to be incredibly useful... changing the alert function so that the dialog becomes a confirm window. Clicking cancel means that no further alerts are shown to the user. Great for when you're writin Javascript without a debugger and have to resort to 'alert debugging'.
window.alert = function(s) {
 if( !confirm(s) ) window.alert = null;
}
In case you're wondering... I found it embedded in the comments on this post: http://www.joehewitt.com/blog/firebug_for_iph.php. Cheers Menno van Slooten

Labels: , ,

1 Comments:

At 6 July 2007 14:32, Anonymous mikeh said...

Great, isn't it!

Python is the same, I think you'd really like it if you started playing with it.

Example :

def bark():
print "woof!"

class Dog:
pass

dog = Dog()
dog.speak = bark

dog.speak() # outputs "woof!"


And it's not just with objects either, functions can be passed around in this manner :

def let_anyone_in(username):
print '%s can come in!' % username

def let_mike_in(username):
if username == 'mike':
print 'mike can come in!'
else:
print 'Go away, %s!' % username

def is_allowed_to_come_in(auth_function, username):
auth_function(username)


is_allowed_to_come_in(let_anyone_in, 'rob')
is_allowed_to_come_in(let_mike_in, 'rob')

outputs :

rob can come in!
Go away, rob!

(the indentation is messed up as I can't put pre tags into my comment.)

 

Post a Comment