|
|
|
|
|
by Jare
5004 days ago
|
|
Nothing in general, but the way it is used for this tutorial adds nothing and obscures some of the topics. Original jQuery code: var canvasElement = $("<canvas width='" + CANVAS_WIDTH +
"' height='" + CANVAS_HEIGHT + "'></canvas>");
var canvas = canvasElement.get(0).getContext("2d");
canvasElement.appendTo('body');
'Native' code: var canvas = document.createElement("canvas");
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
var context = canvas.getContext("2d");
document.body.appendChild(canvas);
Similar misgivings about the use of a jQuery plugin to read the keyboard later in the article. |
|
* 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:
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: