Hacker News new | past | comments | ask | show | jobs | submit login

It's not good jQuery code either.

* The naming convention is terrible. 'canvasElement' sounds like it would be the canvas element, yes? No, it's the canvas jQuery object!

* Use of hard-to-read string concatenation.

* Use of .get(0) - use [0] instead.

And some non-jQuery objections:

* Unfortunate line continuation style that is hard to maintain (What if you change the length of the canvasElement variable name? You have to re-align it!) and falls apart in a proportional font.

* Inconsistent use of single vs. double quotes. I recommend single quotes for JS strings and double quotes for HTML attributes. Do it the other way around if you prefer, but at least pick one and stick with it!

* I'm reading the code out of context, but I'm guessing that CANVAS_WIDTH and CANVAS_HEIGHT are "constants". Why are they being used directly in the code like this? Shouldn't this code be wrapped up in a function that takes those as parameters?

Ignoring that last objection for the moment, I might write the jQuery version like this:

  var $canvas = $('<canvas>'), ctx = $canvas[0].getContext('2d');
  $canvas
      .width(CANVAS_WIDTH)
      .height(CANVAS_HEIGHT)
      .appendTo('body');
You're right, of course, that in this particular example jQuery has little or no advantage over direct DOM manipulation, but if they are going to offer a jQuery example, it ought to at least be a good one.

BTW the $ prefix on a variable containing a jQuery object is a very common practice in jQuery code. It's especially useful when you need both the jQuery object and the corresponding DOM element (assuming a single-element selector like '#foo'). Then you can use $ on the jQuery object and the same name without the $ for the DOM element:

  var $footer = $('#footer'), footer = $footer[0];



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: