Skip to: Navigation Content Search


Declaring functions in JavaScript May 8th, 2008

Well, here’s a little tip for you if you didn’t know already. Some people say that there are a couple of ways of declaring functions in JavaScript and you can go to town doing one or the other (depending on your tastes) because they do precisely the same thing.

Well they do and they don’t.

Tell me why this will work:

<html>
<head>
   <script type="text/javascript">
    noodles();
    function noodles() {
      alert("Do you like noodles?");
   }
</script>
</head>
</html>


And not this:

<html>
<head>
   <script type="text/javascript">
    noodles();
   var noodles = function() {
      alert("Do you like noodles?");
   }
</script>
</head>
</html>


The second example will return our favourite word: undefined.

Maybe obvious to you, but not to me when I first got on the bandwagon. You see the browser will look at all function declarations (that is, the function in the first example) first and think, “Hey, these might be useful!” and then proceed to store them in a little hidey hole for use later. Then it will go on and do everything else. So when the browser encounters a call to a function it already knows what to do.

In the second example, we’re just assigning a function to a variable, which is great, but the browser has to know about it before we execute. In other words the execution must come after the variable declaration. It’s like trying to do this:

   alert(noodles);
   var noodles = "I love noodles!";

It’s just something to keep in mind.

On WWWriting April 28th, 2008

Here’s an exercise we were taught in writing school to help free our minds from the conciseness and blandness used by politically-correct trogologytes with nothing better to do than to force us all to use non-figurative, monosyllabic grunts expressly devised to be comprehensible to a sock puppet.

What you do is think of someone you know well and write ten metaphorical sentences about them. It starts by thinking:

“If my friend were a vehicle, what type of vehicle would he/she be?”

The answer might be something like:

“She is a wheat harvester on its back wheels.”

The idea is taken from a poet, whose named I cannot remember, who used this device to describe English poet laureate, Ted Hughes.

For example, here’s one I made up about a person I know:

His shoulders are two oversized furcoats, draped over a telegraph pole.
His voice, a shotgun ringing through a bowling alley on a Saturday night.
His eyes blink over an early evening at the equator.
He uses his nose like a vacuum cleaner sucks up marbles.

As you can see, you can create a fairly vivid image of a person through the association of ideas. My example is rubbish, but give it a go, it’s not only simple but fun - like throwing a hair dryer in the fish tank.

Party on with the Youtube JavaScript API April 16th, 2008

Spewing out Youtube videos on to your page has just become easier. Now you can load, control and search Youtube videos using nothing but JavaScript and a bit of patience. I know, I know. Your excitement is palpable through my DSL exchange.

So what can you do? You can embed two players onto your page:

  1. The chrome player - with all of Youtube’s standard controls
  2. The chromeless player - you guessed it, with no controls

For some, probably sane reason (although I’m yet to ascertain why), when using the chrome interface you cannot load new videos into the same player using the loadVideoById function, which is available to the chromeless player. Therefore if you would like to employ this highly useful method and be able to control playback, you have to build your own controls. Fortunately, the API methods make it rather easy.

Having nothing to do one rainy day, I decided to give it a go. My motivation was related to the fact that we go to a lot of parties but neither I nor my lazy friends are bothered to bring music and whine incessantly if we have to change a CD. Given the wealth of music videos on Youtube these days I thought that I could make a rudimentary jukebox so that you can play and cue music at will, even when plastered on tins of lager.

Naturally, it will play whatever video you feed it, but I don’t really want to watch some inane mashup of the Star Wars movies dubbed to a Linkin Park sountrack or other shit. One application that I thought might be rather splendid would be to create a playlist to join all the parts of a movie or TV episode. I am grateful to all the folk who take the time to splice and upload these treats but, by no fault of theirs, it’s  a chore to click to the next part every nine minutes and twenty four seconds.

Here’s my first attempt. Of course I will excuse myself with the following:

  • it’s alpha
  • code review to come
  • design change inevitable (maybe in the shape of a jukebox, that would be original)
  • predictably, I couldn’t give a wet sock if it worked in IE6
  • ideas for the future: saveable playlists, editable playlist order using sortable behaviour, auto-download of next video for smoother playback, fullscreen (or bigger at least), save /cache searches, tally favourites, plug into last.fm for recommendations, get artist data from musicbrainz, blah blah

At the very least, it’s great for listening to music at work.

Peeing on flies April 10th, 2008

Ahh, Amsterdam - the watery princess of the North looking up into the oceans. Exuding chaos and beauty through its sinewy canals. Home to a thousand bicycles and iron hooks from which you can dangle furniture from your storage lofts. Magnet for people of all persuasions - particularly young continentals looking to get stoned.

The novelty of Amsterdam takes a few visits to wear down because you’re hardly on the plane on the way back from wherever you came from and you’re planning your next weekend to the city. This of course is due to your still altered state of consciousness whereby you hold the unwavering belief that you could subsist on joints, hot chips and cake for the rest of your terrestrial existence. Reality often kicks in when you are asked to communicate with someone born of the prevailing system and all you can manage is a string of warbling nonsense surrounded by pauses long enough in which to pour a pint of Guinness.

However Amsterdam is more than this: you will notice, if you are a male, or care to frequent the male toilets, that they paint tiny flies on the urinals. The idea is that you will instinctively aim at the fly when you piss and not on the floor, nor presumably on the person standing next to you. This can only mean that people in the Netherlands either take great delight in urinating on insects or on the floor, but not both at the same time.

You can also see the world’s largest collection of working bikes near the Central Station, crammed into a split-level parking lot on the canal. It is a marvel to witness how this modern city functions without reliance on the car, unlike so many other western metropolises. The prevalence of the bike has led to some astonishingly innovative two-wheeled contraptions such as the bike/trailer combination; the “bike for the whole family” bike, with a seat for mum and dad and two kids; and the reclining bike, which is the only personal displacement vehicle in which you can rest, smoke a doobie and exercise at the same time. The unicycle is notably absent.

Diplomatic immunity through JavaScript April 5th, 2008

Would you love to be able to waltz in to a place, piss all over the floor, without anybody saying or doing anything to you? Even if they wanted to punish you, they would have to follow a process that you yourself defined. Haw haw!

Anonymous, self-executing functions can allow you to do this. They’re kind of like diplomatic immunity for your browser and can be very powerful.

(function(){/*
    Oooh it’s so cozy in here. I have access to all
    global variables but I can do what
    I like and no-one will know!
    Now I’m going to do some private things.
*/

var privateVar = “I’m so lonely in here”;
var privateFunction = function(s){ alert(s) };

/*

Okay, maybe I want to share something with the
    outside world but let’s namespace it just in case:

*/

return namespace = {
           publicFunction : function(q){
               return function(a) {
                privateFunction(q + privateVar + a)
               }
            }
};

})();

We can’t access any of the private variables or functions from outside our anonymous function, thus avoiding collisions and overwriting, but we can return public functions that do! namespace.publicFunction is able to see, use and modify our private variables, but only in the way in which we want it.

It’s even possible to throw a bit of curry in there to spice it up. Calling namespace.publicFunction and passing it an argument (in this case a question) returns another anonymous function that expects an argument (an answer) and will then use our private variables to construct a little dialogue.

We would call it like this:

namespace.publicFunction("How are you?\n")("\nThat's too bad");

The example is basic and doesn’t make much practical sense but it demonstrates the way scope works in JavaScript and it can be a simple but handy tool to have in your arsenal.

A flying f*%kup March 28th, 2008

You’ve spent years and swathes of cash planning a major upgrade. Importing the best engineers, business consultants, designers and researchers, you’ve planned your project down to the finest detail, assessing risks, inviting all the right stakeholders to contribute and undertaking stringent testing procedures before launch.

There are no cutting corners and no getting it wrong - you’re upgrading once of the most important and most highly trafficked sites in the world and any downtime would have a severe effect on a large number of people.

Going live - the moment you’ve been waiting for for what seems like years has come. Are we ready? Have we checked all the systems? Is everyone trained on how to deal with the infrastructure and networks? Is our backup plan prepared?

“Ok! Flick the switch!”

Nothing.

“Flick it again!”

Still nothing.

The pressure is mounting. Complaints start to trickle in. Your visitors are wondering what is going on as there is no service. Total chaos ensues.

No, I’m not talking about a website now, but Heathrow Terminal 5. My trip to Amsterdam to see Mark Knopfler in concert, planned months ago, has been thwarted by “a catalogue of errors“.

A Romanian Easter March 26th, 2008

“What types of agricultural goods does your country export?” is not a typical ice breaker you’d use in conversation, but in rural Romania, where every square metre of land has been tilled for some purpose, it’s a serious question. And they expect an answer.

The relationship between people and land is more evident in Romania than any European country I’ve visited. Transylvanian roads are dotted with locals selling essentials such as eggs, turnips, faggots (bundles of sticks), home-made wines and cheeses, baskets and a products from every exploitable environmental resource. The land is their livelihood, their playground and sadly their rubbish tip.

Man at Bran markets

While conservative with their consumption, Romanians seemed liberal with their wastage. Along the roadside, the fields are littered with plastic bags and bottles. Spectacular snow-capped mountains and forests are connected by rusted pipes than run across the landscape towards the giant cooling towers of industrial towns. Indeed the country has a run-down air about it: outside Bucharest the buildings appear exhausted and stained; high-density apartment blocks queue beside abandoned factories apparently waiting to collapse to make way for the next generation. Spurts of EU funding are visible: dual carriage ways connect major centres, although it is still common to share them with donkey-drawn carts carrying wood, manure or entire families.

Coming from western Europe, Romania appears insanely cheap. You can feast on a local dish of grilled chicken with ham and garlic potatoes, polenta and mountains of fresh bread, a few litres of Ursu (the local beer named after bears) for around £7 or 30 RON (Lei). The average Romanian wage for a worker in a city company we were told is something in the vicinity of 500 Euros, with the rest of the country receiving a lot less, but they survive because inflation is low and so is the cost of housing. But people are nervous about the shift to the Euro which they say will drive up the prices, like they did everywhere else.

The low wages are probably why Romania jammed with Romanian tourists - it’s just too expensive to travel elsewhere. The castle of Bran where the Royal family once lived and, supposedly, Vlad Dracul, teems with Romanian travellers and their families with the odd Spanish or French and even Australian (!) making up the minority of gawking, photo-carrying pilgrims. Nevertheless, always on the look out for a business opportunity, market owners sell their homogeneous wares in these areas hoping to entice tourists to buy tacky Dracula mugs and t-shirts, wooden swords and vampire teeth.

Doing business in Romania is a rather informal affair which might come as a surprise to unsuspecting westerners who expect contracts, offices or even business names. In Romania these commercial excesses are optional. The rental car dealer from which we hired our 4WDs (one of which wasn’t a 4WD) consisted of two gents in full denim with bad teeth in the car park. They were nice enough and didn’t try to con us, although at 250 Euros for each car, we knew they had the better end of the bargain.

The hostel in Bucharest, which we found only by luck since there was nothing external to indicate that we’d arrived, was a converted house or nunnery with only three rooms, each fitting eight people. Even the girl working at reception was forced to sleep in a plastic banana chair behind the desk. About to retire for the night, I passed her thinking that she was taking a rest,

“Feeling tired?”

“Yes, hopefully tonight I’ll be able to get some sleep”, she said and smiled as she then proceeded to prepare her make shift bed out of what I’d have felt uncomfortable on after one hour (even after a dip on some sun drenched beach, a margherita and a 15 minute massage).

Our attempts at speaking the local language were met with mixed reactions. According to our taxi driver in Bucharest, who thought it would be a riot to hear four foreigners stammering instructions in Romanian for quarter of an hour before revealing that he spoke English, told us that half the country spoke English to some degree. His claimed seemed rather dubious in our experience. In Brasov our linguistic repertoire was tested on numerous occasions - our local corner store consisted of a half-metre square hole in the wall and was run by a friendly lady in a grey apron with a profound patience for the warbling of foreigners. The fact that we couldn’t see what we wanted to buy thwarted our usual method of pointing and thrusting money in all directions however our pronunciation of lapte (milk) and pâinea (bread) must have been half close as both products were handed to us with efficiency.

I was impressed with the way Romanians were interested in the world beyond their borders. At a remote petrol station, the same guy who had inquired about the state of primary industry exports in Australia also informed me that he’d learned English from the television, and much of it from an Australian drama called McLeod’s Daughters, which was hugely popular in Romania. His lack of twang in his accent made me suspicious, but to his credit, his spoken English was good. I watched some Romanian television while there and can admit that I didn’t experience any of this osmotic effect with the exception of picking up that the word crap means carp and that fried crap is an infinitely entertaining item to read on a menu.

Romania is known to have the largest population of European bears roaming around the wilderness. We didn’t see any but we did see many dogs. There are hoards of them, everywhere. Our guide books reported that there were 200,000 stray dogs in the country, but it seemed like a gross exaggeration when we looked about. You’ll see dogs in the cities rummaging through bins for food, sleeping dogs, lone dogs simply sitting in a fields doing nothing or marauding packs. There are dogs of all breeds (although mostly of the mongrel variety) and sizes. The strange part was that most of them seemed healthy unlike their best friends who, in the rural areas, were weathered and bent from whatever struggle they’d endured throughout their lives. Perhaps it was a symbol that, even in a former impoverished Eastern block country, there are opportunities to be had by the tough and street-smart.

I’d go back to Romania in a second. Everyone was very nice to us, even the policemen who pulled us over for going 70 in a 50 zone (even though we were driving at the same speed as the lorry filled with turnips in front of us) and only gave us a warning despite our licences not being valid. And the country side, beyond the rubbish is in some areas untouched and pure. What really impressed upon me though is the air of optimism - it’s a country that is growing and having joined the EU last year, you get the feeling that the people suddenly feel part of a world that for so long seemed to be passing them by.