Please visit my new campsite listing site ukcampingmap.co.uk


Archive for the ‘Computers and all that’ Category

Updating plugins to use the new jQuery.on event binding method in a backwards compatible way

Friday, January 6th, 2012

I’m going through all my written/half-written/never really gonna get written properly probably jQuery plugins to ready them for the new jQuery plugins site. While I’m at it I’m updating as many event handlers as I can to use the new $.on method (as other event binding methods are likely to be deprecated in future).

This presents a problem as I would like to achieve backwards compatibility too. A simple solution for the bind method is:

var binder = $.fn.on ? "on": "bind";
$(this)[binder]("click", handler);

But I’ve also put together this more generic solution (this is completely untested, but something like this should work)

if(!$.fn.on) {
   $.fn.on = function(events, selector, data, handler) {
       if(typeof selector == "function") {
           return $.fn.bind.call(this, selector);
       } else if(typeof selector == "object"){
           return $.fn.bind.call(this, selector, data)
       } else {
           return $.fn.delegate.call(this, selector, data, handler)
       }
   }

   $.fn.off = function(events, selector, handler) {
       if(typeof selector == "function") {
           return $.fn.unbind.call(this, selector);
       } else {
           return $.fn.undelegate.call(this, selector, handler)
       }
   }
}

Find that campsite!

Sunday, May 8th, 2011

I’ve been very busy lately. Busy making it easier for YOU – yes YOU! – to find the perfect campsite in the UK.

As of a few days ago, my campsite listing website has some new features. And not just any new features – these are (to the best of my knowledge) unique new features. The already pretty handy map of campsites now lets you…

  • Filter campsites based on what facilities they have – you can either specify that your ideal campsite must have a certain feature, or definitely must not have it. Ideal for finding a campsite that allows campfires but no pesky caravans.
  • View only those campsites that are open during the month you’re planning on holidaying.

There are one or two additional features hopefully to go live later this month, but for now please take a look and let me knnow if you have any feedback.

Two small but useful javascript facts

Monday, February 28th, 2011

Bees kneesPassing parameters into setTimeout callbacks

setTimeout (and setInterval too perhaps?) accepts a third parameter, an array of parameters to pass in to your callback function, so

setTimeout(function() {
myFunction(need, to, pass, these, in);
}, 200);

Can far more efficiently be written

setTimeout(myFunction, 200, [need,to,pass,these,in]);

Firebug’s console still works when you’re at a breakpoint (and can be very useful for debugging jQuery)

When debugging using firebug  and you set a breakpoint, when your code stops at that breakpoint

  • you can still use firebug’s console to run any code you like
  • “this” in firebug’s console is always set to what “this” is set to in your code

This means that you can play around with your variables at will at any given point in your code. It may be that I was a dunce for not knowing this, but I’ve never seen anybody I work with take advantage of these facts, so maybe it’s news to more people than just me…. and it’s bloody useful so I feel no shame in shouting about it.

For instance jQuery, for all its benefits, can be a pain to debug due to the fact that so much work is done by a single string (your selector) and on a single line of code (using chaining), and that jQuery often doesn’t give very helpful error messages. This means if you wnat to debug a certain line you have to either a) keep stepping in and out of the murky world of jQuery’s inner methods in order to find out where and why the unexpected bug is happening; or b) add temporary lines to your code which carry out only part of the single jQuery line, then reload the page to observe if they succeed or fail.

Not so if you set a breakpoint and then use the console. For instance, say a fairly complex line of jQuery misfires.

$(">p input:focus", myContainer).css("height", adjustHeight).children(".shrinker").remove().end().wrapAll("<div class=\"done\">");

By setting a breakpoint in my code on this line, and then copying the line into the console and running it, I can progressively remove/tweak bits until the error no longer appears; I never have to step through jQuery’s code and I never have to reload the page. Easy peasy.

How do, DOS

Thursday, February 17th, 2011

Much like recent activity on this blog, my involvement with the windows command has been characterised by being entered into begrudgingly, generally taking a lot longer than I intend, and leaving me thinking that there’s something better I could be doing with my time.

You see, I’m not really that much of a geek – I own very few gadgets (quite possibly none, unless a mandolin counts) and find playing around with computers tedious (one reason I’m drawn to front-end development is it’s far removed from the confusing and arcane inner-workings of the computer). My family didn’t own a computer back in the 80s, when typing in commands at the prompt was the norm, so the whole experience is alien to me.

But, as of today, I’ve lost my fear… thanks to the humble batch file.

For anyone who doesn’t know what a batch file is, it’s a file which runs a series of command line statements. It has a .BAT file extension, and basic ones are very easy to write – the syntax is exactly the same as typing into the DOS command line itself… except you’re typing in a nice text editor so trivial things such as using ctrl+v to paste, using the cursor keys to move anywhere, and clicking and dragging to select text work. And, best of all, you only need type your commands once, into the batch file, and then just click on it (or a shortcut) next time you want to run it.

So, for example, every time I wanted to minify CSS and JS on one of my localhost sites before an upload to the live server I used to spend 5-10 minutes typing, making mistakes, swearing and crying. Now I just click an icon, and don’t feel the need to swear or cry half as much.

Fonts are not quite the enemy

Wednesday, February 16th, 2011

Today I learned that there’s a lot more to using fonts  in a website than just including them with the @font-face declaration, and that maybe typekit has its uses after all.

I also learned that if I use a “Today I learned…”,  terse but link intensive format to write blog posts I’m more likely to bother to share something useful (at least this once). So more brief but bountiful posts to follow… maybe.

Eventful times

Friday, October 22nd, 2010

I’ve just started delving into using jQuery’s custom events. They’ve been around for a while, but I never really saw the point of using them before; I’d read one or two nice examples of how they can be used, but I kept hitting a mental block when trying to think of ways to use them in my own work. I think, like the great leap forward you have to take when realising an object can be as abstract as you want (eg a process that exists only fleetingly, such as an ajax call, can be an object), programming using events as a central aspect of your style requires a big change in the way you think about problems.

As an example, previously I was always saving references to objects that a given object might need to interact with, e.g.

function Obj1() {
   this.container = $("#container");
   this.child = new Obj2(this);

   this.method = function() {
         //do something
   }
}();

function Obj2(parent) {
   var that = this;
   this.parent = parent;
   this.container = $("#childContainer");
   $(this.container).click(function(){
       that.alter();
   });

   this.alter = function() {
      this.altered = true;
      this.parent.method();
   }
}

var obj1 = new Obj1();

So what’s wrong with this? It’s difficult to say, but it always jarred with me that you had to pass in “this” as a parameter in order to make it easy to track back to the parent. And there will be circumstances where you’re creating an object that has to interact with lots of other objects and you have to either pass in lots of parameters when creating the object or do some on the fly processing to find the objects that need to be affected.

Now, here’s the same thing achieved using custom events

function Obj1() {
   var that = this;
   this.container = $("#container");
   this.child = new Obj2();
   $("#childContainer").altered(function(){
       that.method();
   });
   this.method = function() {
         //do something
   }
};

function Obj2() {
   var that = this;
   this.container = $("#childContainer");
   $(this.container).click(function(){
      that.alter();
   });

   this.alter = function() {
      this.altered = true;
      this.container.trigger("altered");
   }
}

var obj1 = new Obj1();

Ok, so what’s so good about this? It may even use more lines of code. But crucially it gets rid of having to store references to objects, freeing you up to create ever more complicated applications without having to create a web of dependencies that is difficult to maintain*. A good analogy I think is to think of an object triggering an event as a child shouting. If the child shouts when it needs something then it doesn’t have to constantly hold its parent’s hand; it’s parent comes to it on hearing the shout. And this gives the child freedom to explore the world on its own terms, and develop into a more rounded, unstifled human being… but I think I’m straying off the point.

So to sum up, javascript/jQuery custom events are a very useful feature.

And don’t smother your progeny.

*I’ve just re-read the API and found out that you can attach all manner of data to the event as extra parameters, which will also be very useful for this.

Batch including headscripts and links in Zend Framework

Thursday, September 16th, 2010

A bit of a dull post to break my silence with, but after a summer away, it’s back to the grindstone of earning a living through programming. Fingers crossed I’ll be given the opportunity to work again on a website I finished ages ago, fixing all the things I did badly and adding some enhancements.

I used Zend framework for the back-end of the site and first time around I had a very rudimentary grasp of how to use it, but no real in depth understanding of its finer points. I’m now finding that I did a lot of things the long way round (eg typing out JSONs by hand  rather than using the Zend_JSON class to build them automatically). One major bugbear I had was that I was adding all my javascript and css files individually to the document head, and that the syntax for doing so in Zend wasn’t really any more concise than just hard coding <link rel=”stylesheet” ….

So now I’m revisiting Zend the first thing I’ve done is write a couple of view helpers to batch add javascript and css files, which I thought I’d share here.

<?php

class Zend_View_Helper_IncludeStyles extends Zend_View_Helper_Abstract {

   public function includeStyles($folder)
   {
     $results = array();
     $handler = opendir(getenv("DOCUMENT_ROOT") . "/css/" . $folder);
     while ($file = readdir($handler)) {
       if ($file != "." && $file != "..") {
         $this->view->headLink()->appendStylesheet('/css/' . $folder . '/' . $file);
       }
     }
     closedir($handler);
   }
}
<?php

class Zend_View_Helper_IncludeScripts extends Zend_View_Helper_Abstract {

  public function includeScripts($folder)
  {
    $results = array();
    $handler = opendir(getenv("DOCUMENT_ROOT") . "/js/" . $folder);
    while ($file = readdir($handler)) {
      if ($file != "." && $file != "..") {
        $this->view->headScript()->appendFile('/js/' . $folder . '/' . $file);
      }
    }
    closedir($handler);
  }
}

Cam****

Friday, May 7th, 2010

What a great day for the United Kingdom of Great Britain and Ireland. I think every man woman and child of this nation will wake this morning with new hope. Hope that the mistakes and missed opportunities of recent years will finally be undone. Hope that, from now on, we will all be armed with a new freedom, a new ease of living our lives without constraint by the petty failings of tired and out-of-date thinking.

I am of course talking about my new website, of which version 1 is now released

ukcampingmap.co.uk

It’s seems like an obvious idea, and I for one can’t believe no-one else has done it yet (particularly as I’ve been ruminating over it for the past two years): All the UK’s campsites plotted on a google map. So much easier than trawling through directories of campsites available elsewhere on the internet, that have only rudimentary or difficult to use tools for finding a campsite in the location you want one.

It has a search (for postcodes, towns, villages, tourist attractions) and also has easy navigation for viewing a single region, county or tourist area (eg Snowdonia).

There’s plenty more work to do on it, but for the first time, after a few weeks of intense work*, I have something fairly stable which is, while still very basic, still a lot easier to use than other campsite directories.

Enjoy.

Oh, and God help us now the  Tories are in!

*well, maybe an hour a day

We know where you live

Wednesday, April 28th, 2010

I read recently that mozilla have been making efforts to fix a bug whereby a website can find out which sites you’ve visited previously, which has implications for user privacy. On the same day I began to notice that there was something very sinister about… the google ads!

It’s a fairly innocuous ad, it would seem, but it occurred to me that the site I was looking at – the site I’m working on at the moment – had no content related to Javascript or web development at all. As I was at work i had, however been visiting umpteen javascript sites all morning. Surely Google wasn’t serving me ads based on my browsing history?

To test the theory I decided to visit a site all about puppies, and on my return, lo and behold, what did I see:

!!!

A bit of investigation led me to confirmation that Google do give publishers an option for their ads to

… display ads based on interest categories that might appeal to your users. For example, if a user browses many sports-related websites displaying AdSense ads or watches sports-related videos on YouTube, Google may associate a sports interest category with their cookie and show the user more sports-related ads.

I didn’t write about this immediately largely because I wasn’t sure how bothered by it I was. It’s very easy to rail against advertising on the internet as being too intrusive, but then again advertising does pay for the, largely free, internet. It’s always a trade-off.

Arguing by analogy would seem to shed light on the issue. Imagine, if you will, a magazine that showed you adverts about dog leads just after you walked your dog, showed you adverts for sky sports subscriptions just after you went to watch the football etc. Or billboards that magically change as you walk by to display ads you’re uniquely susceptible to. A bit of a dystopian image… but then again, technology often throws up moral dilemmas caused by the new possibilities it opens up and arguing that “in the old world it wouldn’t be OK” often makes down-sides seem bigger than they are. It would be sinister to be surrounded by morphing billboards… but that’s not what google ads are.

… but after a couple of weeks of being aware of what google are doing, and seeing the same adverts over and over again, no matter waht the content of the site I’m on, I can’t help but feel a few sinister overtones. In addition I can’t help feeling that Google are giving sites in their advertising network an unfair advantage. If a site about puppies is able to show people ads based on their past behaviour rather than the site’s content then they profit from google sharing (albeit indirectly) information about me that the puppy website, cute though it may be, has no right to use.

Yes, I know the boundaries are blurred. It’s not wholly dissimilar to when a magazine enlists market researchers to find out about its readers, and then uses this information to attract advertisers. And I know Google don’t pass on any data to the puppy website, and that no-one’s forcing anyone to click on ads. And that there’s an argument that more relevant advertising could even be a good thing for the consumer as well as the trader. But it still has a distinct whiff of unfair play about it. Insider trading. “Don’t tell anyone I told you this, but something tells me your next visitor might click on an advert for shoes. Nudge, nudge. Wink, wink. Click, click. Kerching”.

Google have taken a lot of flak lately about their lack of respect for users’ privacy when rolling out  Google Buzz. They’ve also been in the news over their fisticuffs with china and their publication of data of which governments have asked them for data/removal of data (I can’t decide if the fact they don’t publish the Chinese data due to the government there considering it to be a state secret undermines or reinforces its effectiveness). But it’s amazing what they can get away with that goes unnoticed.

To end on a positive note, visit this site to exempt yourself from Google’s ad-info-sharing cookies.

Now, go and watch The Birds.

*edit – it turns out this “behavioural advertising”, as it is known, is common practice across many ad suppliers and, somewhat cheekily, it’s an opt-out rather than an opt-in. To opt out of them all visit this site.

http://www.sitepoint.com/blogs/2010/04/06/mozilla-to-tackle-browser-css-history-privacy-leak/

Stooping to the law of averages

Tuesday, March 23rd, 2010

An artist's impression of my perfect office

I’ve got a bad back at the moment. It’s been far worse in the past, so I’m not really grumbling, but I have however recently started my first office job in a long time, and yet again I’m faced with the perennial problem of having a chair and desk that force me to stoop. It’s not actually too bad at this place (the screen will allow me to raise it up to close to eye level, and the non-swivel chair I have is a lot more comfortable than most of the swivellers I’ve sat in), but it has reminded me of a point I’ve been meaning to make for a while.

Years ago, when attending health and safety training, we were told that you should be careful to make sure your seat is at such a height that your legs touch the floor comfortably. Why exactly this is good for your back I don’t know, but I presume somebody knew what they were talking about. For employees with legs too short to reach the floor (does Tom Cruise work in anyone’s office?) the advice is to put a box or, if you’re gullible, and expensive footrest on the floor.

However, at the opposite end of the spectrum you have those people who, like me, have legs so long that raising the chair up to a suitable position for the legs means the torso gets lifted up way above the table, almost as if a hot air balloon were involved. This means that I have to lean forward a lot to type, even more so if the screen height can’t be adjusted much.

The worrying thing though is that, because I am only a slightly taller than average man, these people consist of a sizeable portion of the population – a bit less than half of all men and some women too -  all of whom have no option other than to stoop and wreck any chance they had of making it to retirement without suffering a slipped disk.

And finally to my point; this situation is caused by the fact that desks are made at a height to suit the average person, which is fair enough for the general office. But what frustrates me is that in IT (and probably other male dominated professions too) you don’t get higher desks, even though the average height of men is greater than that of the population in general. All these bluechip IT companies spend hundreds, if not thousands, per employee on getting them the latest, trendiest, most ergonomic chairs, keyboards, mice etc…, but it’s all for nothing if the desk is still too low.

When I run my own multi-million dollar software company (based on the success of a random muffin recipe generating website) I will proudly place at the top of my ‘work for us’ page

OUR TABLES ARE A FULL 3 INCHES TALLER

Beat that, Google!