Archive for the ‘My Life’ Category

Me…

Posted in 'General, My Life' by James on July 13th, 2010

Okay. For once, I’m going to say what I actually think on this site of mine! I’ve done it to a degree before but I got frequently hushed by the few people that see anything but neutrality as a weakness or a threat. I’m only human, and I have some damned opinions. So here they are!

Be prepared for mildly offensive rhetoric and inappropriate usage of the ellipsis and exclamation mark!!!

  • I think this universe is simply awesome. We’re quite tiny when everything is put into perspective. Heck, we’re just one form of life, on one planet, in one star system of hundreds of billions of star systems in this galaxy alone (which itself is accompanied by hundreds of billions of other galaxies), and yet some people still have the arrogance to feel that the human race is at the centre of the whole universe! Our wonderful yet miniscule existence is aptly covered in this beautifully poetic video from the late Carl Sagan.

  • I think inline documentation, like that made possible with JSDoc, makes code ugly and unreadable. I want to see the code, and that’s all!
  • I love the outdoors. I envy people that have jobs outside. And I don’t mean outside on the street cleaning up human sewage. I mean outside in the real world — the places that we haven’t yet destroyed.
  • I think heavy UI abstractions like ExtJS totally take away all of the fun, excitement and challenges that should form a central part in any programmer’s role. To me, it looks like a product built for business people, and business people rarely understand the motives and desires of programmers — they only understand a couple of things: profit margins and economic viability.
  • I’ve yet to sit in an office chair that won’t make my back hurt like hell after eight hours.
  • I don’t believe in a God. I also don’t believe in fairies or unicorns.
  • I get annoyed when people don’t realise the difference between believing that something doesn’t exist and rejecting the belief that something does exist, for it should be apparent that there is a huge difference.
  • My favourite comedians of all time are Ricky Gervais, George Carlin, Frankie Boyle and Bill Hicks (watch all the videos!).
  • I hate running, but I absolutely love cycling!
  • I don’t understand Node.js. I really did try, but it just ended up confusing me. I’m not a Linux wizz so installing it was trouble enough.
  • I think modern day advertising and marketing techniques are the bane of western society. Oh, and politicians!
  • I didn’t care for the World Cup, and I always find it amusing how people shout at the TV and put flags on their cars when it won’t have the slightest effect on the game itself.
  • I’m trying to become a vegetarian. Watch the documentary, Earthlings, and you’ll understand why.
  • Pixar made me cry. I don’t know how they did it…
  • I’d love to know how to play a musical instrument properly. Preferably the piano.
  • I think humans have a responsibility to stop using non-renewable resources, but I don’t think playing the blame-game is helpful. I also don’t think change will happen given the current political and economic powers that be.
  • I have a love-hate relationship with PHP. Doing most things is dead simple (which is great), but it’s such an ugly language!
  • Even after all this time, jQuery is still my favourite JavaScript library. It’s small, intuitive and doesn’t require me to adopt a new programming paradigm!
  • Other movies that have made me weep like a baby include The Stoning of Soraya M, Forrest Gump, The Champ and Pay It Forward.

Okay, that’s enough for today. Comment if you want. If you disagree with me on any of these points, then, GOOD! This world would be such a dull place without such varied opinions and people!

Pong, and what it taught me

Posted in 'JavaScript, My Life' by James on October 29th, 2009
Pong, and what it taught me

For those of you that don’t know, I’m currently studying Computer Science at the University Of Kent. As our first programming assignment we had to create a game of Pong (see screenshots here) using Java and a 2D-graphics platform called Greenfoot. It was a challenging and interesting assignment, within which I was able to discover many new things about Java and about general game development.

In my opinion, Java’s insistence on a class based approach makes it a fantastic programming language to start with, albeit being quite hefty, in terms of the sheer quantity of available classes. I also liked the fact that most of my knowledge of JavaScript could be applied to Java. There are a few syntactical discrepancies that left me confused, but all the foundation concepts were (more or less) the same.

I thought it’d be fun to port my Pong game over to JavaScript. It was painlessly quick to do actually, and it’s the first time I’ve ever built a game with JavaScript and the HTML5 canvas tag/API. You can head over to the demo to play it for yourself, and feel free to have a look at the source code. It’s not quite as sophisticated as the Java one, I didn’t have time to add cool graphics or a scoring mechanism. And yes, I know it’s the wrong way round – we were told to do it that way!

What I discovered

It’s a frame-by-frame thing

One of my very first revelations was that, to create a game, it’s important to think about everything on a frame-by-frame basis. Every new frame is a fresh slate upon which you reflect the various states represented in your program. The relationship between any two frames depends on a persisting programmable interface that “remembers” previous states.

It all becomes wonderfully simply when you think about it in this way… move the ball one cell to the left, if its position is equal to zero then it must be at the left wall, therefore we can bounce it off the wall! (okay, so it’s not actually that simple – you have to take the ball’s width into account)

It’s a massive contrast from ‘event-driven’ development, wherein you wait for the user to make a choice and then carry out something following that. In the Pong game, I’m not waiting for the user to do anything – on every new frame I simply query the necessary information to make stuff happen. For example, If the left cursor key is currently down then move this (paddle) one cell to the left! (I’m not waiting for the user to press the left cursor key, each frame is being drawn regardless.)

Everything’s an object

In my Pong game, each physical object in the game is represented as an object within the programmable layer, each one an instance of a predefined class. For example, there’d be one Paddle class from which two Paddle instances (“objects”) would be created, each representing a single physical paddle on the screen.

OOP really shines here!

Abstract, but not too much!

Abstraction really is very important, especially when there are tonnes of things that need to be happening at any time. What I actually mean here, is that it’s important to separate out functionality between your methods. This is obviously better:

Trying to learn Java

Posted in 'General, My Life' by James on July 22nd, 2009
Trying to learn Java

I’m off to University in just over a month and I thought it’d be a good idea to get a head start, academically. I’ve applied to study Computer Science, and, as only sense dictates, the first language we touch upon will be Java, the big brother of JavaScript… kidding; I can hear Crockford screaming! So, with all this spare time I’ve decided to learn Java, or, at least begin on the journey!

I downloaded Eclipse and the “Java runtime”, only, of course, to find out that I already had about 10 different Java runtimes already installed. I fired everything up and then stopped; I had absolutely no idea what to create… What can I say? The command-line doesn’t excite me! Yes, I know pretty much anything can be created with Java, even hardware-accelerated games, but all the beginner-tutorials out there only show you the monotonous command-line drivel.

I also purchased a book recommended by the University; I believe it’s the one we’ll be learning from in the first year. It’s called “Objects first with Java” and goes into a tremendous amount of (unnecessary?) detail; I haven’t really got past the first few pages. I’ll tell you something about objects; you’re never going to learn squat about them from tutorials or books. Yeh sure, you’ll get an idea about what they are but you’ll never appreciate the abstraction provided by OO language until you dive in.

Now, don’t get me wrong about this whole University thing; I am looking forward to the “experience” but I’m not exactly overly-excited about the impending course material. I haven’t even begun and I’m already finding it dull; I’ve no doubt that I’ll be pleasantly surprised though… I’m sure the first lecture will prove enthralling!

I’ll be honest with you; I’m only going to University because “that’s what one does after school”. Heck, most people go to Uni for exactly the same reason (they just don’t know it); it’s what’s expected of us. You can say what you want about it but essentially, University is yet another device used to extend and perpetuate the status-quo; i.e. us working and the government getting richer. I just can’t wait; out of uni with a load of debts and then into the monotony of a “career”. Eventually I’ll have additional burdens that will require monetary attention and before you know it I’ll be where most of the British upper-middle-class finds itself, paying off debts… living the dream!

Isn’t it amazing, I haven’t experienced any of this impending fate yet and I already have the capacity to be utterly dismissive and totally negative about it all! Here’s hoping the grass is greener!

I’m on Github!

Posted in 'General, JavaScript, My Life' by James on May 16th, 2009
I’m on Github!

Yes, finally I’ve joined the masses on Github and I plan to sporadically share special things on there, starting with the following recent developments:

“literalHTML”

A tiny but powerful modification allowing you to specify HTML/DOM structures inline in your JavaScript code, an example:

var className = 'active';
var myMenu = |
    <ul>
        <li class="{className}">Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
|;
 
// myMenu is now a DOM object:
myMenu.nodeName; // "ul"
myMenu.childNodes; // [ <li.active>, <li>, <li> ]
 
// Do something:
jQuery('body').append(myMenu);

View here »

“getDescendants”

Something I required for a project; a function to gather all descendant-elements down until a certain depth is reached:

<div>
    <ul>
        <li>Something <strong>interesting</strong></li>
    </ul>
    <p>Something <span>else</span></p>
</div>

Examples:

var div = document.getElementsByTagName('div')[0];
getDescendants(div, 1); // -> [ <ul>, <p> ]
                        // i.e. children
getDescendants(div, 2); // -> [ <ul>, <p>, <li>, <span> ]
                        // i.e. children + grandchildren
getDescendants(div, 3); // -> [ <ul>, <p>, <li>, <span>, <strong> ]
                        // i.e. children + grandchildren + great-grandchildren

View here »

I’ll hopefully be adding to the repositroy with new exciting discoveries in the near future; visit my profile and “follow me” to stay updated!

Things you may not know about jQuery

Posted in 'Cool Stuff, JavaScript, My Life, News' by James on February 19th, 2009
Things you may not know about jQuery

I was going to do a bit of a series, releasing a jQuery tip every day or week or something, but I think I’m a little too lazy to commit to something like that. So I’ve compiled them all into one post! I’ll probably add to the list at later dates so make sure to bookmark it!

Do you have a tip nobody knows about? – Add it in the comments…

  • $.fn is just a shortcut to jQuery.prototype.
  • You can test if a jQuery collection contains any elements by trying to access the first element, e.g. if($(selector)[0]){...}.
  • jQuery normalizes the event object across all browsers! Have a look at all the available properties/methods over here: http://docs.jquery.com/Events/jQuery.Event.
  • When you create a plugin you have access to the jQuery chain’s previous object:
    jQuery.fn.doSomething = function() {
        this; // => $('a')
        this.prevObject; // => $('li')
        // Remember chaining in your plugins:
        return this;
    };
     
    jQuery('li').show()
        .find('a').doSomething();
     
    // You could even create a new 'root' plugin:
    // (Returns the 'root' of a chain)
    jQuery.fn.root = function() {
        // Root is always document so we have to 
        // go back to one before the last:
        var root = this;
        while(root.prevObject.prevObject) {
            root = root.prevObject;
        }
        return root;
    };
     
    $('li').find('a').children().root(); // <= $('li') is returned
    // Using root() is the same as using end().end() in this situation
  • You can namespace events! This is especially useful for plugin development:
    jQuery.fn.myPlugin = function() {
     
        // Clean up after yourself!
     
        jQuery.myPlugin = {
            cleanUp: function() {
     
                // Remove all click handlers binded
                // as a result of the plugin:
                jQuery('*').unbind('click.myPlugin');
     
                // ALternatively, remove ALL events:
                jQuery('*').unbind('.myPlugin');
     
            }
        };
     
        return this.bind('click.myPlugin', function() {
            // Do something...
        });
    };
     
    // Note, you can also namespace data:
    // E.g. $(elem).data('whatever.myPlugin',value);
  • You can access all event handlers bound to an element (or any object) through jQuery’s event storage:
    // List bound events:
    console.dir( jQuery('#elem').data('events') );
     
    // Log ALL handlers for ALL events:
    jQuery.each($('#elem').data('events'), function(i, event){
        jQuery.each(event, function(i, handler){
            console.log( handler.toString() );
        });
    });
     
    // You can see the actual functions which will occur
    // on certain events; great for debugging!
  • jQuery natively supports JSONP (‘JSON with padding’) which effectively means you can make cross-domain "Ajax" requests (although not strictly Ajax since it doesn’t use XHR). For this to work the requested domain must have some JSONP API in place (it must be able wrap the JSON with a specified callback function). An example:
    function getLatestFlickrPics(tag,callback) {
        var flickrFeed = 'http://api.flickr.com/services/feeds/photos_public.gne?tags='
                       + tag + '&tagmode=any&format=json&jsoncallback=?';
        jQuery.getJSON(flickrFeed, callback);
    }
     
    // Usage:
    getLatestFlickrPics('ferrari', function(data){
        jQuery.each(data.items, function(i, item){
            $("<img/>").attr("src", item.media.m).appendTo('body');
        });
    });
  • You might find it a little messy but jQuery enables us to create an entire DOM structure within a single chain:
    // Create and inject in one chain:
    jQuery('<div/>')
        .append('<p><a href="#">Foo</a></p>')
        .find('p a')
            .click(function(){
                // Do something...
                return false;
            })
            .end()
        .append('<p><a href="#">Bar</a></p>')
        .find('p:eq(1) a')
            .click(function(){
                // Do something else...
                return false;
            })
            .end()
        .appendTo('body');
  • Accessing the DOM elements within a jQuery collection is incredibly easy:
    var HTMLCollection = $('div').get();
     
    // Alternatively, if you only want the first element:
    $('div').get(0);
    $('div').get()[0];
    $('div')[0];
  • Not only can you bind events to DOM elements; you can also bind a custom event to ANY object!
    function Widget() {
        // Do something...
    };
     
    var myPhotoWidget = new Widget('photos');
     
    jQuery(myPhotoWidget).bind('photoAdd', function() {
        // Custom event handling...
    });
     
    // Trigger event:
    jQuery(myPhotoWidget).trigger('photoAdd');
  • Finding the index of a selected element is very easy. jQuery gives us the ‘index’ method:
    $('table tr').click(function(){
        // Find index of clicked table row:
        var index = $('table tr').index(this);
    });
  • You can create your own filter selectors. I did a post on this a while back, but take a look at an example anyway:
    $.expr[':'].external = function(elem,index,match) {
        var url = elem.href || elem.src,
            loc = window.location;
        return !!url.match(new RegExp('^' + loc.protocol + '//' + '(?!' + loc.hostname + ')' ));
    };
     
    // You can now use it within your selectors:
     
    // Find all external anchors:
    $('a:external');
     
    // Find all external script elements:
    $('script:external');
     
    // Determine if link is external:
    $('a#mylink').is(':external'); // true/false
  • I see quite a lot of people still using JavaScript’s FOR or WHILE constructs to create loops in their jQuery scripts. There’s nothing wrong with this but be aware that jQuery’s ‘each’ method can also iterate over arrays and objects!
    var myArr = ['apple','banana','orange'];
     
    $.each(myArr, function(index, item) {
        // Do something with 'item'
        // return false to BREAK
        // return true to CONTINUE
    });
  • The ‘filter’ method accepts a String selector or a function. When using it with a function you must return false to remove the element from the stack and true to keep it:
    $('div').filter(function(){
        return this.childNodes.length > 10; // Must return a Boolean
    });
  • You don’t have to give new elements IDs or classes to reference them later, just cache them into a variable:
    var myInjectedDiv = $('<div/>').appendTo('body');
     
    // Use 'myInjectedDiv' to reference the element:
    myInjectedDiv.bind('click', function(){
        // ...
    });
  • jQuery’s ‘map’ method is incredibly useful, the passed function will be run on every item of the passed array (or object) and whatever the function returns each time is added to the new array, take a look:
    // Create an array containing all anchor HREF attributes:
    var URLs = $.map($('a'), function(elem, index){
        return elem.href;
    });
     
    // URLs = ['http://google.com', 'http://whatever.com', 'http://yahoo.com']
  • This isn’t jQuery related but it can be very useful. When you need to compare two different ways of doing something (performance-wise) you can use the Firebug console to log the time taken to complete a chunk of code, for example:
    console.time('My first method');
    // Do something...
    console.timeEnd('My first method');
     
    console.time('My second method');
    // Do something else...
    console.timeEnd('My second method');
     
    // Firebug will log the time (in milliseconds) taken
    // to complete each chunk...

Reflection on poverty

Posted in 'General, My Life' by James on October 14th, 2008
Reflection on poverty

We tend to throw around the word "poverty" a lot nowadays but do any of us really bother to think about it? I mean, do any of us think about its effect on the world and on us as humans? I for one, don’t! I mean to be totally honest, I very rarely think about the one billion or so people living in absolute poverty around the world!

Not to place too huge a blame on western society but its probably western culture and education that has left me and others so apparently callous and uncaring. Yes, schools teach you about poverty and how massive a problem it is but you don’t hear any teachers or the government telling us go help, no, of course not! This would not benefit the economy!

But then, is this massive issue of poverty something which can be solved with a few extra helping hands? I really doubt it!

Almost one half of the world’s population live under two dollars each day – what an absolutely pitiful amount! How did we, as a species, let it get so bad? Surely evolution is not just about survival of the fittest, surely there is some instinctive drive to help others! If there is then how on earth did we let it get so bad? What happened!?

Maybe we should all pass the blame on to ignorant generations of the past and then forget about it, or maybe it is, in fact, the governments fault (isn’t everything!?)… Maybe every single person on the planet is to blame, even the ones living in poverty! I don’t’ know!

My first “real” job

Posted in 'General, My Life' by James on October 5th, 2008
My first “real” job

Having left school in June I needed a job to make some money over the summer. I was going to settle for something tedious and in-my-view boring like waiting tables at the local restaurant or working at the nearby supermarket, but instead I decided to go further and look for a job which I would actually enjoy.

I’d already been designing websites (mostly personal projects) for about two years, and I’d earned quite a bit off freelancing, so it made sense, since I had the skill set, to look for jobs in the web development/design industry.

Searching online for "web design" jobs yielded rubbish results. Most of the jobs listed were freelance focused or not based in the UK. I would have been happy to adopt a couple of freelance jobs but nothing is more valuable than real industry experience, and that meant getting employed properly for the summer.

After even more searching I eventually came across NMA’s "top 100 interactive agencies". I started at the top of the list, visiting each agency’s website, having a look at their client list, and seeing where they were based. I ended up picking eight agencies, all based in London. I wasn’t looking for "vacancies" because I knew I would be unsuitable for any official listed job. Since I was only looking for an internship to get me through the summer I figured it would be best to simply send some emails explaining this amd hope for the best.

After writing my CV and emailing the applications nothing much happened. Obviously I had to give it a bit of time, so I did…