Javascript Inheritance and callSuper

February 8, 2006 by james

So far I’ve got only 2 problems with the inheritance mechanism from the earlier post.
- it doesn’t allow for multiple inheritance. I’m ok with that…coming from java it is just what I’m used to. However, it doesn’t rule out the possiblility of employing a Class Augmentation approach from being used along with it.
- navigating the prototype chain is tricky. Since the code is ‘resetting’ the constructor property on the prototype…I don’t see a way for program code to traverse the chain (aside from using the non-standard ‘__proto__’ property). This is fine for the code that is aware this is the case…it can look for the ’superClass’ property that the inheritance code is adding…but yeah, thats a ‘gotcha’ for when you are wanting to integrate with another library that wants to (for whatever reason) traverse the chain.

I couldn’t sleep tonight, so I dabbled with adding support for calling overridden superclass methods. It was really more as a fun exercise than anything else as I still don’t see a huge problem with just directly calling the superclass method like so: SuperClass.prototype.someMethod.call(this, arg1, arg2);

So the result is the ability to, from any method (i.e. not the constructor) call this.callSuper(); and it will call the superclasses implementation of the method that you are in! You can also call this.callSuperByName(’methodName’); and it will call the superclasses implementation of the method with the given name. It is intelligent enough to begin searching the prototype chain from the depth that the code that called the ‘callSuper’ method is located.

I’ll post the code soon…need to get ready for work (and I want to make sure it works in more than just one browser :) ).

Prototype Chain

February 5, 2006 by james

I’m doing a presentation on OO Javascript to Daugherty developers on the 27th. In preparation I was doing some digging online (mostly to make sure I really DO know what I’m talking about) when I ran into an article that talked about the prototype chain. While I was aware of this…I don’t know if it was ever spelled out for me…it was just…there. So it got me thinking about a different way to handle subclassing.

There are 2 primary forms of subclassing I’ve seen:
- Copy the methods from the SuperClass.prototype to the SubClass.prototype
- Set the SubClass.prototype to a new instance of the SuperClass.

I use the first and it actually works pretty well. The only problems I have with it are that it (probably?) won’t work with the instanceof operator (actually…I’ve never used it. I just learned about it, but I’m guessing it doesnt’ work), and that it gets hairy when you do multiple levels of inheritance and are trying to keep track of the heirarchy (so you can do stuff like super.someMethod();). But honestly…both of those are probably smells anyway. Don’t subclasses always know who theier superclass is anyway? The SubClass code could just say: SuperClass.prototype.blah.call(this, argv);…not ‘pretty’, but it works. The point is, that the subclassing via copying methods from the parent prototype works, but it still has its problems.

The second I’ve never liked. What if the SuperClass constructor needs arguments? What if it does something expensive, or needs the DOM, or any number of problems. The ’solutions’ I’ve seen to this are to add code to the SuperClass constructor to determine if it was called with no args. If it was, then do nothing. But really, this is only feasible for a constructor that takes args…what if it was a no-args, but did something expensive…or assumed some state of the browser that is not true at the time of the ‘extend’ call?

For whatever reason, the article about the prototype chain triggered something and got me thinking about a different approach. My first attempt was to just set the Subclass.prototype.prototype to the SuperClass.prototype. That didn’t work. I needed to know more, so I dug into the ECMA 262 spec…not sure why that hadn’t happened before. The spec talks about an IMPLICIT (i.e. not accessible) ‘[[prototype]]’ reference. In essence, every instance ALWAYS knows what prototype it was created based on. The prototype chain heavily relys on this implicit reference to resolve properties. This means that the prototype instance on the SubClass should really have a reference to the SuperClass.prototype for it to truly take advantage of the OO features that ECMA script is defining.

So, at face value that means setting SubClass.prototype to a new instance of the SuperClass. I still don’t like that. However, this is Javascript…where everything can be dynamic. So a new idea was forming. Why not create a new, in-line subclass of the SuperClass and set the SubClass.prototype to an instance of THAT in-line subclass instead? Here is the idea:


Class.extend = function(SubClass, SuperClass){
var innerSuperClass = function(){};
innerSuperClass.prototype = SuperClass.prototype;
SubClass.prototype = new innerSuperClass();
SubClass.prototype.constructor = SubClass;
}

This approach seems to be the best of both worlds…it builds a nice prototype chain, and does not require the SuperClass to be overly careful about calls to its constructor.

Is there something I’m missing here? Is there something about this approach that is just..bad, that I may have missed. Please let me know. I’m sure I’m not the first to do this. Until hearing otherwise, this is the approach I will be using.

Suprising taste of success

January 31, 2006 by james

‘Pffft’. Sweet. The wonderful sound of CO2 escaping from a 12oz amber bottle of beer being opened. Not just any beer…the first bottle from the first batch I made. Actually…the only batch I’ve made so far. Oh…and it’s good…really good. Which totally suprised me actually, considering the comedy of errors that unravelled while I brewed. As the man says: “Don’t worry…relax…have a home brew”.

I’d been looking into home brewing for awhile. I met several people who were home brewers and tried a few. Plenty of research on the web learning about the whole process only made me want to do it more. A turkey fryer seemed to be the way to go for the pot and flame to cook the beer in. So I made it known that I was interested in having one and got an AWESOME one from my in-laws for christmas. It’s a great fryer…super safe, 7 gallon capacity, automatic safety shutoff (when its too hot or tilts), it’s electric, and has a submerged heating element (ok…now you seasoned home-brew pros keep your snickers to yourself…for now).

I went out right away and got the equipment from a brew-shop(ish) (I went to Worm’s Way…which is great…just a little corner for home brew though). I got the big kit, complete with carboy (big glass jug for the non-brewer readers) so I could actually see the active fermentation. Connesiour’s “Nut Brown Ale” sounded good, so I grabbed it up, and in so doing, had the ingredients for the beer that would be my first batch.

The kit came with 2 books on home brewing…one of which was the Papazian book (”the man” behind the quote above), which has aparently been read by every home brewer. I read it…at least the first section for beginners. It takes you through the basic info and all the steps for the first batch.

One fateful friday night (January 6, 2006 to be exact), I was ready. Everything was sanitized and the turkey fryer was all setup on the counter…awaiting its time to shine. The batch got rolling with a gallon and a half of water poured by the measuring cup full (4-cup capacity). The red-light kicked on as I dialed the 150 degree temperature into the fryer knob.

Popped the top on the extract can (it was sitting in hot water to make it a bit less thick and more managable) and slowly poured/scooped the thick syrup into the warming water. It promptly sank to the bottom…completely covering the coils. (ok brewers…the snickering may commence…maybe I should have sought a bit of advice before-hand). Panic? No, not yet. I tried to vigorously stir the batter off of the coils and get it to dissolve with a rubber spatula. That wasn’t working, so I thrust my overly-sanitized hands/arms into the fryer (kids, do NOT do this at home…those coils are HOT). This was working…at least better than the spatula. I was able to get my fingers under the coils to move the goo around and away from the coils somewhat. It was beginning to dissolve, but not fast enough. The coils were beginning to scorch the extract that they were touching. Panic. Out of the frying pot and into the carboy.

The carboy was topped off with cold tap water. “Don’t worry…relax” I kept thinking, everything will be fine. Jack was helping me out and we gave the carboy a good vigorous rolling/shaking to get it all mixed up. The carboy cap sucked. It was one of those orange ones with 2 short capped tubes coming off of it. It kept leaking and I had to keep it constantly squeezed…”are we doing this right?”

Standing back I beheld the beer. Time for the yeast. Wait…the temperature needs to be below 70. At this point I was following 2 recipes: the one that came with the extract and the instructions in the Papazian book. I didn’t have everything I needed for the Papazian instructions (namely the dried extract) but I was trying to follow his advice wherever possible.

The kit came with a floating themometer, so we figured it was meant to be pitched into the carboy (sanitized first of course) so in it went. Hmmm…can’t read it through the dark beer (we felt pretty dumb here). After some looking, and a bit of ingenuity, a hook was fashioned to fish out the thermometer. Success. The kit also came with a stick-on themometer, so we held it up to the carboy and it was off the chart. The wort (”wert”…the cooked beer) was too hot. There is a huge double-utility sink in the laundry room that came with the house…it is PERFECT for home brewing. So we took the precious hot beer cider down to the sink for a nice cold bath.

It took about 2 hours to cool down to about 68. In went the dry yeast…straight from the packet. Later while reviewing both recipes I saw that I should have dissoved the yeast in pre-boiled water first. Oh well. The carboy was given another good couple of strong agitations again as I cursed the crap-cap the whole time. When we were satisfied, the carboy was moved to its final resting place in a nice dark corner on a make-shift workbench constructed with 2 saw-horses and a closet door.

We tried to take the specific gravity reading with the hydrometer (like a thermometer…but measures how thick the liquid is relative to water, and in-turn what the alcohol content is). Without any other good ideas, we tipped the carboy and poured some out through the cap into the hydrometer flask. Took a reading of 1.030. Sounds good…time to wrap up.

The book and web say that the first 3 days is super active and the beer will actually foam over, out of the carboy. So they suggest rigging a blow-off tube. Great, maybe that is what those capped tubes on the carboy cap are for. Nope. The tubing won’t fit. Hmm…how about this drilled stopper? Perfect. The tube was shoved into the stopper and the stopper into the carboy. The other end of the tube was laid into an empty bucket so that the foam would escape into it. I later read that this should have had enough water to cover the end of the tube to act as kind of an oversized airlock…so that bugs/bacteria/random yeasts wouldn’t get into the beer. Oh well.

The hard part was done. Now the yeast would feast on the sugars from the extract and make the beer. Time to clean up the mess.

The next day there was 1 inch of foam: it was working! The next day, nothin. Hmm…that’s not right. Give it a good shake. Foamed right up and even out the top a little. Third day…nothing. This is when the blow-off setup comes down and a small airlock is put on. Over the first week I gave it a little shake once…then another about mid-way through the second week. I just never saw any activity. No bubbles in the airlock. There was the build-up of cake (dormant yeast) on the bottom of the carboy though…and it smelled good, so I wasn’t all that worried. I later read that the beer should be disturbed as LITTLE AS POSSIBLE to avoid getting too much oxygen in the mix. Man…I can’t get anything right :) Nothing I can do now…lets just keep going.

Bottling time came and I was ready with 2 cases of 12 oz amber bottles. The kit also came with a bottle washer that is rigged to the utility sink. I love the bottle washer. When I picked up the bottles (again from Worm’s Way) I grabbed some light dry malt extract to prime the bottles with (priming is when you add sugar to the beer right before bottling…giving the remaing yeast something to chew on…and since it is air-tight in the bottles, the CO2 byproduct will carbonate the beer). The caps were boiled and the priming extract was prepared and siphoning was about to commence.

First, the hydrometer flask was filled with beer from the siphon and a reading was taken: 1.020…hmmm…higher than I’d expected. Well…what’s it taste like? Go ahead…give it a taste. Bottom’s up. Wow…that tastes awesome! Let’s get this stuff in bottles! While the beer was being siphoned from the carboy into the priming bucket (where I had already poured the dissolved priming extract), I sanitized the first case of bottles. I love the bottle washer.

The siphon job was done about the same time as my sanitation work. So the priming bucket was moved up to the workbench and I readied the siphon for bottling. The priming bucket came equipped with a spiggot specifically for bottling. But I figured it would leave an inch in the bottom of the bottle (have since learned that if this was used as a fermenter, then that 1 inch would be the un-wanted cake anyway) so I opted to just siphon the whole thing.

Bottle siphoning takes some learning. Beer will get on the floor…but hopefully not too much. After about 10 beers (bottled…not drunk), I had the hang of it. I pulled the box full of un-capped, beer-filled bottles up onto the workbench and grabbed for my first victim. A cap was randomly plucked from the pile and carefully placed onto the bottle. Red butterfly capper in hand I married it to the top of the cap and in one swift but careful motion the levers were lowered and an audible click was heard. My first bottle was capped.

I made pretty quick work of the rest of that case, but the first bottle was set aside. Taking the advise of Papazian, I marked all the caps with a sharpie…numbered them even: 1.01 NBA -> 1.24 NBA graced the tops of the first 24 bottles (NBA = Nut Brown Ale). 1.01 (the first one bottled) was marked with a red sharpie…to distinguish it.

While that case was being capped, the other case was sanitizing, so I rinsed those and went to work on siphoning and capping them. The siphon gave a gurgle about mid-way through the 48th bottle…signaling the end of the batch. Exactly 48 bottles. I finished getting them capped and carefully placed the 2 cases under the workbench. It should be 7-10 days before they are really ready to drink…giving ample time for the carbonation to take place.

That was 5 days ago…I didn’t have the patience. I popped the top of one of the beers tonight for dinner…and man, was it good. And this isn’t like sweet-lemons good…it’s damn good. I normally drink Newcastle Brown Ale…or Boulevard Unfiltered wheat to give you an idea of where I’m coming from. It may be close, but I think I might prefer my batch over the Newcastle.

So, even with all the “mess-ups” this batch was a success. Here’s to even better batches to come.

Named Inputs

January 13, 2006 by james

So, I’ve found myself leaving the ‘name’ attribute off of form elements recently…mostly due to laziness since I’m not using them (I know, I know…unobtrusive, and accessibility). We’re doing an RIA in a closed environment, so we can make the assumption/requirement that the client has javascript enabled. So, most of our stuff is leaning heavily (not quite obtrusively…but it is required) on javascript…and we use css and behaviour to identify the elements in the page and dwr to communicate back to the server. Works fine…great even. The problem is that it isn’t easy for the testers to test it with their robots. My first reaction is that the robots should be smart enough to find the elements by css (like we do)…or at least if it cannot determine a unique css selector for it, ask the tester to provide one (most appear to be automated, text-based scripts). But then again, this would also say to me than any screen readers would have trouble too. Since we aren’t concerned with accessibility (at least to the level of screen readers), that doesn’t bother me too much. The testing problem really does. So, we’re going to need to (at some point…hopefully soon) go back and name all our form elements (or maybe do something automated).

Anyway this whole post was triggered because I noticed that firefox’s ‘form cache’ feature (where if you refresh a page…not reload…just a simple refresh, then the form keeps the values you had in it…not sure if it happens on a back button use) gets confused when the form elements do not have names. I kept seeing values for field a (user name) showing up in field b (some date field).

Moral of the post: use names in the form elements…even if you dont ‘need’ them.

:scriptEnabled

January 12, 2006 by james

I was just reading a little walk-through on styling a select box and it got me thinking about “What if css was enabled, but javascript was disabled?”. Granted, his solution does get around the problem (he only hides the selects that have a classname that is set by javascript…so if you don’t have js enabled, you still see the select). Anyway, I was wondering if there could be a more generic solution to styling things differently based on whether scripting was enabled. Would a :scriptEnabled pseudo-class be a good idea? Obviously we can’t do that, but we could have a scriptEnabled css class that gets slapped onto the document.body element by a bit of script. Then our javascript-assuming styles could be written as:

body.scriptEnabled select{
display:none;
}

I like the idea. Now, is that mixing style and behavior too closely? Maybe, but I still like it. Proceed with caution though…I wouldn’t want to wind up over-doing it and doubling all my rules…one for .scriptEnabled, and one without.

FACE

December 21, 2005 by james

FACE seems to be making the rounds today: http://kurafire.net/projects/face. I was elated when I saw them using the class attribute to tie in the behavior…but then later worried about how much is crammed into it. We all agree that separating presentation (css) from data (semantic markup) is important…I think that FACE is violating a separation of the data from the behavior. With face you have a css class that looks something like this:

class=”C:myClass:10:L:20:50″

Each ‘node’ there is a property that describes the animation. The animation code will effectively add and remove a css class to an element (or set of elements) based on the specified intervals and properties. Which is cool, but I think its too close to the markup: its IN the markup. I understand that part of the goal of FACE is to be as simple as possible, the developer doesn’t even need to learn or know javascript to make it work. However I’m concerned about the cost of this goal. I now need to modify the markup to modify a behavior/animation and I feel that that is a violation of separation of concerns.

I think a very, very simple set of javascript could achieve something like this. One could have a script file dedicated to setting up the FACE animations for the page or even the site.


Face.animate(’#enhance’, ‘myClass’, 10, ‘L’, 20, 50);

The animate function could use behaviour.js or cssQuery.js to locate the node indicated by the selector (first argument) and then run through the animation sequence as it does now…this really just changes the method of starting the animation to be more direct (the developer could have more control over when the animation begins) and (more importantly) the details about the animation are more removed from the data. Also, with this approach, there would be no need for the #enhance element…or the quirky way to have multiple animations on the page (indicated by a comma separated list of ids as the last node in the #enhance elements FACE css class descriptor). The developer could use whatever css selector best identifies the element to animate using the css classes and ids already defined in the markup. And the Face.animate function could be called for however many elements need to be animated.

Replacing by tagname

November 13, 2005 by james

I managed to crunch some stuff out this morning. Stitch now has the ability to identify and replace content by tag name. so, and html file:

<html>
<body>
<p class=”user”>John Doe</p>
</body>
</html>

and a stitch rule file:

p{
  content:$userName;
}

Running the template like so:

Template t = new Template(html, rules);
Map data = new HashMap();
data.put(”userName”, “Snoopy”);
String out = t.render(data);

“out” would be:

<html>
<body>
<p class=”user”>Snoopy</p>
</body>
</html>

It can traverse mult-level hash maps in the model as well as bean properties (so…basically like jsp expression language references). Not terribly useful yet…need class selectors to really become more useful. For now though, there are some refactorings to be done.

Progress on Stitch Parser

November 6, 2005 by james

Took most of the weekend, but I now have a parser that will recognize the following:


pain{
display:none;
}
agony{
border-color:red;
margin:$user.name;
padding:$user;
}
.dog{
border-color:red;
margin:$user.name;
padding:$user;
}
#cat{
padding:$user;
}
#mouse .blah{
padding:$user;
}
#mouse p{
padding:$user;
}
#mouse p.short{
content:$user.name;
}
#rat p .blah span:if($owner.address){
content:$user;
}
hope:if($user.boss){
display:remove;
}

You can probably see some of my frustration coming out in some of the names. I’m better now…really. I have one “lexical nondeterminism” right now…which should be fairly easy to overcome…but not tonight.

Firefox Password Manager

November 6, 2005 by james

Am I the only one that can’t stand the way the Password Manager doesn’t let you tab to the other buttons? Pisses me off…

StringTemplate

November 4, 2005 by james

I may not have emphasized enough in the previous post how much I really like what Terrence Parr is doing with antlr and StringTemplate. This article (especially the linked article on Enforcing Strict Model View Separation in Template Engines) really made me realize some bad things about the template engine I was starting to write (specifically around the conditionals). So, now the conditionals look something like this:

#user_name .boss:not($user.boss){
display:remove;
}
#user_name .boss{
content:$boss_salutation;
}
#favorite_song:if($user.favoriteSong){
content: $user.favoriteSong;
}
#favorite_song:not($user.favoriteSong){
content: $unknown_song;
}
/* shorthand for the above 2 selectors…if first arg is empty, second is used as default */
#favorite_song{
content: $user.favoriteSong, $unknown_song;
}

And the StringTemplate actually has me wondering whether I should write a new one at all. I think Stitch (note to self…probably should get a name…ctrlTemplate?) still adds some value over what StringTemplate does, by fully separating the markup from the rules about how the data is to be inserted into the document…and then the rules file being in a format that is VERY similar to css, a format most web designers should be very familiar with. Then the markup can change quite drastically so long as the ‘css’ rules still match (mostly ids and class selectors), and the rule file need not change. I do think that if/when the tempates have a server-side ‘compiled’ version, its very possible it will use StringTemplate.

I was thinking that the ctrlTemplate could also potentially operate on tree structures too (not just xml/html/xhtml). Like, for example, an AST tree result from a parser of some sort. Just a thought.