Friday, August 28, 2009

Javascript Shenanigans: How jQuery works. Kinda.

Every time I re-read the source code to jQuery I understand something new about how it works. It's actually rather enlightening, figuring out how it works.

I'd like to explain the way the "jQuery" code from the previous post works, since it uses a decent amount of more advances javascript and led me to a greater understanding of the language.

So, this:

(function () {
$ = function(elem) {
return new $.prototype.init(elem);
};
$.prototype = {
init: function(elem) {
this[0] = elem;
return this;
},
each: function(f) {
for (var i in this[0])
f.call(this[0][i]);
return this;
}
};
$.prototype.init.prototype = $.prototype;
})();

Broken down:
First, to make sure that everything is setup as soon as the file is loaded (before any of the document is even parsed by the browser), the setup is wrapped inside an anonymous block. I'm not sure what the proper javascript term for this is, but it's very similar to the "static { }" block from Java, where any code contained within it is immediately executed as soon as the class is loaded by the JVM. As an example:
(function (val) { alert(val); })("HI MOM");
Would immediately alert the string "HI MOM" before any content loads.

After this, we define the $ function. The function does the simple job of returning a new instance of "init". While creating instances of functions may look odd, Javascript allows this. Functions are often used to declare what's commonly thought of as an object. While "function $(elem)" is legal, I find the "var $ = function(elem)" notation makes a little more sense.

Javascript does not formally define its classes, so multiple instances of "object" can each have completely different properties and methods. Properties and methods are assigned at runtime. The .prototype method, mentioned in the previous post gives us a way to make sure all instances of an object have specific members. So, $.prototype is an object containing additional members of the $ object, which will be applied to every $ around.

In it, we define an init method which stores us a reference to the element we gave it, and then returns an instance of "init". After that we define an each method, which simple iterates whatever "this[0]" is and returns. While it's not strictly necessary to return from this function it let's us do something really cool: chaining. Look it up at jQuery's site, it rocks. This each method accepts a single parameter, a callback function, which is executed on each iteration of the loop. Rather than simply calling the function like "f()", we can use the more flexible .call() method. This basically allows us to "redefine the execution context for the given function", or in simple terms it lets us change the value of the "this" variable.

This final line adds $'s prototype to init as a prototype. This is why jQuery plugins are written
jQuery.fn.nameofmyplugin = ...
In real jQuery, jQuery.fn = jQuery.prototype, so your plugin adds another object to $'s prototype, which also adds it to $.init's prototype.

g'night. tired. bye.

Thursday, August 27, 2009

Javascript Shenanigans: Why I hate Prototype

Surprise, I'm not dead yet!

So anyway, I've been doing a decent amount of Javascript lately. This includes pure JS, and a few frameworks...jQuery, Prototype, and Dojo. I'm going to ignore Dojo for now since it really is a whole other beast than either jQuery or Prototype.

jQuery and Prototype behave in similar ways, providing a helper function like $() and allowing you a relatively standard API to do things that certain browsers do differently (like CSS). But jQuery is nice in that it stays out of your way, Prototype intrudes. It's the asshole that starts staring over your shoulder and saying everything you're doing is wrong as soon as it walks into the room.
Technically, Prototype grabs your keyboard and starts keymashing.
Odds are pretty good that a pure javascript application will stop working as soon as prototype is included in the page.
Take a look at the following example:

window.onload = function () {
var arr = [0,2,5,7,3];
alert(arr.length);
for (var i in arr)
alert(i);
};
The variable arr is an array with 5 elements. The first alert returns the expected "5", so you would expect that the "For .. in" loop (or a foreach loop) would alert you 5 values. In pure JS it does as expected, but when prototype gets in the game the for loop runs 43 time. Holy hot damn, what just happened to my code? Well, now you can't use foreach anymore because prototype all up in da hizzy.
The root of this problem is in the way that prototype works: by extending the DOM and javascript itself, through the "prototype" method.
In my copious free time I decided to see if I couldn't figure out how each of these frameworks implemented their "each" iterator function.

So, this emulates prototype's behavior:

Array.prototype.each = function (f,context) {
for (var i = 0; i<this.length; i++)
f.call(context,this[i]);
}

Yes, prototype is somewhat more elegant than this, but the basic premise is the same.
While jQuery's behavior is a bit more complicated than this (And I'm pretty certain that this is because John Resig is an immortal space traveler, come from the stars to give us amazing client side scripting languages), I feel it offers a better way of achieving the same effect.

(function () {
$ = function(elem) {
return new $.prototype.init(elem);
};
$.prototype = {
init: function(elem) {
this[0] = elem;
return this;
},
each: function(f) {
for (var i in this[0])
f.call(this[0][i]);
return this;
}
};
$.prototype.init.prototype = $.prototype;
})();

This allows you to iterate over the array in much the same way, except it doesn't modify the array so our original example would still loop 5 times and not 43.
But why does it work? Next time, on Build Environment.

--PXA

Saturday, June 6, 2009

Level 3, BEGIN

So it's been a long time since I've written anything, and that's because since I last wrote here I got a full time job, graduated from RIT, and moved to the Boston area. But now I have some time and figured I might as well put something up.

Right now, my brand new Palm Pre is syncing a small selection of my music library from iTunes, which in and of itself it kindof cool. The iTunes syncing is amazingly easy, but I'm going to hold judgement for now until it finishes. If it got my contacts it'd be sweet. The rep at the Sprint store was able to sync from my iPhone several things, but I didn't see the contacts list. We'll see if iTunes syncs them. I did add my facebook account and as promised it created a contacts list from that information, but I was driving at the time so I didn't see if they were combined with other contacts.

On first impression I'm a little ambivilant about several aspects of the phone. I like the weight and I don't mind at all that it's a little thick. But the slider and the keyboard feel a little cheap. Although the one handed mechanics of the slider are great. On the software side of things, finding certain settings is a little odd sometimes, but the app catalog is ULTRA easy to use. And the phone is FAST. Everything is FAST, loading new applications, quitting, backgrounding, switching, using. It's all so very smooth.

WebOS 1.0.2 is out, I'm going to update to it.

Saturday, April 11, 2009

In which goals are fulfilled, part 2.

It is now after 1am, and I have returned from my Scotch tasting at my friend's house. We lined up several grades of Johnnie Walker Scotch, as well as an Islay single malt called Caol Ila. The center pieces being the Blue label and Caol Ila.
I broke the foil seal and uncorked my bottle. Sniffing the cork and the top of the bottle, I got my first hint of what I'd been coveting for a long time. The smell of peat was immediate, followed by a nice soft oak and an undercurrent of an almost syrupy sweetness, like maple syrup or grenadine. I couldn't get anything more out of the smell other than whisky and soft.
The taste of it, cut and uncut, was delicious. Everything that came through in the smell, everything I always imagined GREAT Scotch would taste like was there, and all in perfect balance. Not too much of anything, or not enough. Wood, smoke, earth, sweetness, apples, nuts, spices, vanilla. It was all there, sitting nice and warm in my mouth.
I'm afraid I lack the professional taste to fully describe the whisky, all I know is that it is was really worth the wait. It may be the smoothest and most well balanced whisky I've ever had.
For now it will stay on my shelf, only to be enjoyed in the best of company.

--PXA

Friday, April 10, 2009

In which goals are fulfilled, part 1.

Almost since I've been drinking, I've drank whiskey. Not exclusively, but after a few months of the obligatory cases of mass produced Beer of Questionable Quality, my first real purchase request was for whiskey. Any. Since then my palate has become more discerning. My 21st birthday gift to myself was a bottle of The Glenlivet 12 year single malt Scotch. Today, I purchased a bottle of Johnnie Walker Blue Label blended Scotch Whisky. Since I began reading about Scotch, this particular name was mentioned over and over again, for taste...quality...class. I've desired this whisky for years.
I decided to buy the bottle about a week ago. My tax returns had arrived and I filed for my final RIT tuition refund, I was feeling rather minted. To this effect I placed an appointment in my Exchange calendar titled simply: It's time.
I waited anxiously through the week, until finally Friday afternoon rolled around. I left work with a good friend of mine, who shares my appreciation for fine whiskeys, and collected my better half, who shares my appreciation for fine states of inebriation. We went to a local liquor store, whose staff have come to recognize me due to the intensive research I usually put into my purchases. The store's owner was busy ringing out another customer, so I approached the other register and stated a request I'd been waiting to make:
I'd like a bottle of the Johnnie Walker Blue Label Scotch.
The store owner heard this, and immediately stated that he would be helping me today.
A few minutes later he returned from the back with a blue leather case, and set it on the desk. He opened the two clasps on the box, and opened the lid: revealing my bottle of Scotch, and small leather booklet. I paid, which was anticlimactic. I wish I'd have had the foresite to visit my bank and get several $20 bills.
I returned home and opened the case, the smell from the inside is a rich scent of age, class, and wood. Something I haven't smelled in years, not since I had the fortune to open the case of a very old and very expensive violin. I never had the pleasure of playing that violin, but tonight I will have the pleasure of drinking this Scotch.

Good things come to those who wait
--PXA

Thursday, March 5, 2009

Name NASA's Node 3 Contest

So I noticed something today on Facebook: A group for the purpose of altering the outcome of the contest NASA is running to name the ISS Node 3 module, so as to name the module the Colbert.
I voted and then noticed the names the NASA has proposed as well as the write-in's. Some of them have a pretty decent comedy value.
Here's the list.

Earthrise, Legacy, Tranquility, Venture, Vision, Hope...all lame. Ignore them.

Serenity, clearly winning. But consider why most people are voting for it. The Serenity is a ship of pirates, named after the pivotal lost battle of a lost war. It is constantly in disrepair, barely kept running from stop to stop and only then by girl-genius mechanic Kaylee. Ok, maybe a bad namesake.

Enterprise. Seriously, stop naming things after the Enterprise unless they're gonna be epic. The Node 3 is an over glorified bathroom and air filter. Not epic. Picard wouldn't even shit in this thing much less captain it.

Xenu. Are you serious? I appreciate the irony of naming something which would have a positive impact on the lives of several people with very public lives after the fictional "bad-guy" in the creepiest religion to be created in the last 100 years...but really? Xenu? On the ISS? Well, he is from space.

Vista. This is obvious. Naming the Node 3 after the worst technical and public relations screw up in the history of Microsoft? Seriously, people hated the Bob less. Do you want this thing to crash and burn?

Buddy. Ok. Makes sense. It fits the purpose of the module. Really nothing to say except IT'S LAME! BUDDY! Might as well call it Bob!

Synergy. It makes sense, matches the purpose, and follows the feel of the names before it. ...It's better than Buddy.

Horizon. Sorry guys, this is way to close to "Event Horizon" for my liking. We all know how that ended.

At least no one wanted to call it Miranda.

Thursday, January 22, 2009

The Real RIT, thoughts and concerns

So I haven't posted in a while, so I figured I'd writing an editorial about some RIT stuff.

SG recently challenged several RIT administrators to live in the dorms, eat at Gracies, walk the quarter mile, and park without a reserved pass. I unfortunately couldn't make it to the closing meeting, but I did read through the blogs that were posted by the administrations and they seemed very positive. I'm not sure they got the "full" experience. It seems the admins completely missed out on several joys of campus living I got to experience.

1. 15 hour days. The reason sleep schedules are so odd in the dorms is because of how hard students have to work to survive. Between classes and work, some of us start at 8AM or earlier and don't get to put face to pillow until almost midnight. When you're looking at something like that, try to imagine what video games at 3am feel like. NOW try to go to Gracie's and eat that salad or that wrap, after a long day of frustrations that started way too early.

2. Sexile. It happens, even at a place like RIT. I bring it up because of its affects primarily on morale. Yes it keeps you up sometimes, and sometimes keeps you from getting into your room to do your work. But unless you get your own chance to do some sexiling, being forced to do your work in the hallway or the lounge because your roommate is bumping uglies is a pretty crushing blow to your morale. Couple that with the bonechilling cold of walking the quarter mile in winter and all the other frustrations of life at RIT (Parking, bad professors, over priced food, class registration, etc) and you have a recipe for a miserable existence.

3. Parking. Someone had to say it. It was part of the poster. When did these administrators have to deal with THIS daily thorn in my side? As far as I know, never. Actually, from what I read on the blogs, they marveled at how easy it was to walk to their offices from the dorms. SG, what gives? I wanted to see Destler tooling around E and F lot in his Prius for 20 minutes trying to find a spot not marked reserved. These administrators have dedicated parking or easy access to reserved passes, in the spirit of the challenge shouldn't they have had to deal with parking like the rest of us do? Yes, this is the DORM challenge...but why would you so obviously ignore commuters? Personally, I'm a little disappointed by this.

4. Food outside of Gracie's. Yes Gracie's is bad, we all suffered but then moved on. Unfortunately the food on the rest of campus isn't particularly good...or more to the point, fairly priced. It really puts my nuts in a twist to go to the SAU and see people running the line to grill twice as fast as people going to the Deli, walking out with these greased up cheeseballs that cost worlds less than getting a salad and yogurt. Living at RIT, going to class, suffering the weather makes it hard to WANT to eat healthy, and the PRICE makes it hard to afford eating healthy. It's crap. Sure administrators can deal with it since they pull down some decent change, but what about the student employee limited to 20 hours a week for minimum wage? The cost of good food on campus hurts.


And I'm sick of writing. Go go gadget "Publish Inane Rantings to Public" button.