Archive for the ‘javascript’ Category

Finally Posted Code…and I’m moving

February 23, 2006

I got the Javascript Inheritance code uploaded: Class.js

I’ve been keeping pretty busy getting our house ready to sell. About 2 weeks ago we found a house in U. City that we love…put an offer on it and it was accepted. Pending all inspections and such, we close March 30. So…we now have to move up our plans to sell our own house and do a few years of upgrades and painting in a week or so. So far Aislinn has been really busting her butt painting EVERYTHING and I’ve been remodeling the master bathroom and fixing random other things (and breaking others :) ). I’ve gotten pretty comfortable with plumbing too. Then there is the presentation on OOJS on Monday. It’ll be fun, but so far, finding time to prepare has been almost impossible.

SO, about the code (if you haven’t been following the posts on it). The Class.js file provides an implementation of Classical Inheritance for Javascript. It does not involve newing up an instance of the superclass to set as the subclass’ prototype…I really didn’t like that approach. The implementation still builds a nice prototype chain though. It basically create’s an inline function…then sets that function’s prototype to the superclass prototype. Then it news up an instance of that inline ‘class’ and sets the subclasses prototype to that instance. So the prototype chain for instances of the subclass still actually contain a reference to the superclass’ prototype.

The code also adds a callSuper method to the subclass’ prototype. callSuper can be called from anywhere in the subclass and will result in a call to the superclass’ implementation of whatever method the call resides in (actually…it will find the first implementation further ‘up’ the ancestor chain…not neccessarily in the superclass). So, effectively, it knows how to find the overridden version of the calling method…and calls it. For Example:

function Shape(){
}
Shape.function.toString = function(){
return "Shape";
}
function Square(){
}
Class.extend(Square, Shape);
Square.prototype.toString = function(){
var str = this.callSuper();
return str + ': Square';
}

A Stab At Javascript Inheritance

February 8, 2006

Here is the working code for implementing an inheritance model in javascript. Most of the code is actually for handling the callSuper functionality (calling an overridden method in the super class). The actual subclassing code could be reduced to 4 lines if that bit were removed. Just highlights the “are we sure we need this” question. But its DAMN cool…and I had fun, so it was worth the time.

This script requires arguments.callee.caller to work…that is the magic the code uses to figure out where in the prototype chain to begin the search for the super class’ implementation of the method currently being called. There were some minor tweaks I had to do to get it to work in IE, but it works. As a bonus, calling the ‘callSuper’ method from a constructor will work too.

I’ll probably wind up putting this in a library sometime…I just wanted to get it here and get some eyes on it. Enjoy
Update: I removed the code because it looks horrible on here…I’ll upload and provide a link when I have proper access.

Example Code…this is sickeningly basic…but its what I used while I was putting this together. I’m not sure why I didn’t fire up jsunit to do this thing right (tdd). Oh well…I blame the insomnia.


function Shape(){
this.shapeCalled = true;
}
Shape.prototype.toString = function(arg){
return ‘Shape ‘+arg;
}

function Rectangle(){
this.callSuper();
this.rectangleCalled = true;
}
Class.extend(Rectangle, Shape);
Rectangle.prototype.toString = function(){
var mssg = this.callSuper(’test from rectangle’);
return mssg + ‘ : Rectangle’;
}

function Square(){
this.callSuper();
this.squareCalled = true;
}
Class.extend(Square, Rectangle);
Square.prototype.toString = function(){
var str = this.callSuper();
return str + “:Square”;
}

Update: Finally posted the code here: Class.js. Getting a house ready to sell will keep you busy :)

Javascript Inheritance and callSuper

February 8, 2006

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

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.

:scriptEnabled

January 12, 2006

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

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.

Parsers…

November 4, 2005

I’m burnt a bit. Need a break. I think I have a basic idea of how I want to proceed. Basically just a css parser (ast tree output) and the html parser with the visitor pattern. Visit each node and traverse the AST tree for all matching css rules…for each match append an annotation to the html node. Then have another pass that will actually generate the output. At least as a start.

I’ve been looking at ANTLR quite a bit and I’m pretty impressed. It looks like ANTLR 3 will use the StringTemplate ‘engine’ for generating the actual code. The idea is that you could feasibly have 1 grammar and multiple output templates to render the grammar in different languages. Exactly what I was looking at maybe having to write…thank god because it looks like they know a hell of a lot more about lexers/parsers/compilers than I do…and I like where they are taking it (MVC separation). So I may evenually have 1 css grammar that would generate a parser for java, jsp, perl, javascript, php, ruby, python…etc. Awesome.

I also found it interesting how closely css syntax resembles the syntax used in the grammars and the string template files…

Behaviour, JSAN and Events chat with Nate

September 6, 2005

Just chatting with nate about a few of his recent JSAN and Behaviour posts…his site was down when I tried to comment on them…so I’ll post the chat session here.

James: cool.
did you read this?
http://openjsan.org/doc/c/cw/cwest/JSAN/0.10/lib/JSAN.html
esp the section on namespaces.

nminshew: yes, that is where I got my examples and such.

James: I take from that page that you need to define and explicitly add to the namespace (so a use(’xml.Blah’) wont do anything if xml/Blah.js doesn’t actually have a blah class in an xml namespace.
also about the Behaviour thing…i think you need to be careful about how you’ve done it…I would actually consider it flawed…just by chance that it works. what you’ve told it to register is a hash that IS the function…when behaviour iterates over that hash it is adding rules for the items you’ve defined inside the function…but also properties of the function itself. You’d be much better off by defining the hash directly (as the docs do).

nminshew: Yeah, I guess it wasn’t exactly as I thought it was. That kind of sucks actually, because if you have a complex heirarchy, that can get pretty complicated.
I got that [Behaviour] example straight from the docs. I used their example when I wrote my first app.

James: I’ve never seen that example anywhere. send me a link.

nminshew: Well their site has moved and changed since I first went there, I don’t know if I can find it again, but I’ll try.
I pretty much copied and pasted it though. the window.onload and everything.
Sent at 8:54 AM on Tuesday

nminshew: I can’t find it, but I didn’t come up with the function names and such and wouldn’t of thought to do it that way if it wasn’t for the example.
Also, what is you problem with putting the rules in a function and passing it to the register method?

James: anyway it is was a bad example. I’d change the code to do as it shows on the docs now.


nminshew:
In my example, I should have had () after defineRules.

James: I don’t have a problem with that…but exactly…the way you had it confused me and that was the ‘does this work’ question came from…you were passing a reference to the function not calling the function and passing what was returned….thought it was a typo at first…but the function did not have a return statement.
To make it work such that you can (as you have already changed it to do) call the method is like so:

function defineRules() {
var rules = {
‘a.popup’ : function (element) {
var popupLocation = element.href;
element.onclick = function () {
window.open(popupLocation);
}
element.href = ‘javascript:void(0);’;
}
};
return rules;
}

OR

function defineRules() {
return {
‘a.popup’ : function (element) {
var popupLocation = element.href;
element.onclick = function () {
window.open(popupLocation);
}
element.href = ‘javascript:void(0);’;
}
};
}

nminshew: Yeah yeah, I know, that was another typo I just fixed.
Here’s an example of someone else doing it this way: http://javascript.about.com/library/blonload.htm

James: I’d really recommend that you re-consider the onload thing. a lot of scripts add onload events (in a non-destructive, portable way)….it really makes it easy for me to just take advantage of some lib or module that does so…I dont’ have to know that if i use a module, i’ll need to plug in some boiler plate onload event that will call it…it could get pretty hairy if i’ve got a lot of modules I’m using that have some work to do when the page loads.
that’s [the link] gonna blow away any registered onload events.

nminshew: Well if you do it statically, don’t you run the risk of it executing before all the elements are loaded on the page?

James: I”M not saying do it statically…I’m saying register an event handler (all browsers support what are effectively event listeners…just in different ways). I’m saying register a listener for the onload event on the window.

nminshew: do you have an example of the way you are talking about?

James: yes, i sent the link to you via email yesterday [http://www.scottandrew.com/weblog/articles/cbs-events]. Its what I’ve been using here.
from my code:
addEvent(window, ‘load’, initWidgets);

that adds an ‘onload’ listener to the window object…so when onload occurs, the initWidgets method is called.
(addEvent is the function written by the guy in that article)…actually I somehow found a version that doesn’t have the useCapture stuff…written by a different guy…looks mostly the same just minus that useCapture boolean

nminshew: k, thanks. I’ve just never known a better way of doing it.

James: which is why i thought you’d like to know.

nminshew: thanks.
do you have the example without the useCapture?

James: funny…it’s on the unobtrusive article:
http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html

JSTable cram session

September 5, 2005

I’m putting together a kind of JavaScript TableModel object to facilitate some things on a project at work. So, this is my cram session for it. You can see the ideas change and clarify as it goes.


TableModel is the data.
TableView binds to and inspects the TableModel to determine how/what to display
BeanBackedTableModel has a data object that serves as the backing for the actual cell data in the table.
However, TableModel is PRIMARILY the model for the actual TABLE. So, it holds the state for the TABLE entity. The fact that part of that state may come from an underlying data object is secondary.
TableView must be able to (potentially given the type of TableModel) reconstruct the model only from the (potentially very basic) view representation. So, for example, on an initial page load if there is data in the table by default, that data should be extracted/scraped from the view to initialize/construct the inital model. This feature may also be implemented as an entirely separate object…a TableModelInitializer perhaps.
In the latter case, the TableView that eventually is bound to the same table must be made aware of the inital state (this is why it may make sense for the 2 things to be on the same object.

So, ‘what state does a table have’:
columns
rows
header
footer
caption
summary

(future) support RTL directionality

Stab at a Requirements List:
1. Table Structure CAN still be defined by the markup.
2. Table Sturcture CAN be entirely JS-built
3. JS Table Model can be reconstructed from the markup.
4. JS Table Model (data) can be backed by a JS Domain Object or collection of them.
5. Can add Domain objects directly to the table.
6. Can edit (optionally) the table model (data) directly in the table.
7. Can sort the table model (data).
8. Developper can take an existing static table and easily behavior-ify it (add sortability and even in-line updating) in a declarative fashion.
9. Can handle/do paging
10. Can do static header/scrollable data section.
11. Can break columns into sections.
12. Can have static columns.
13. Support a kind of extension model. new features can be attached to the table model (like drag-n-drop column arrangement, show/hide columns, etc).
14. Completely/easily css styled.
15. Data Model should be easily extracted from table (for ajax update/insert
purposes). Consider ability to distinguish/notify of: rowupdated, deleted, added.
16. Ability to select/deselect rows (be careful with pager integration as well as pager integration with the sort capability). Does this imply a difference between the full data model and the displayed dom model? The pager very much just controls what rows are displayed…it could be made aware of changes to the actual underlying data model. Would sort-order actually modify the data model? or would that too merely be a display thing. So the actualy model is always in initial and insertion order…then the sort ‘module/extension’ keeps the actual sorted model (or index) off to one side and modifies the actual dom as sort requests come in. Well, we have 2 models really…the actual TableModel and the DataModel that backs it. The DataModel could be always kept in insertion order, and the TableModel (SortableTableModel?) could be aware of the order and return the rows in the appropriate order. Then have a nother model for the pager (PageableTableModel?) for the page-ability. Then the models would have to be stackable (decoratable). So you could have a sortable table model that is wrapped by a pagabletablemodel. the getRows function would first be processed by the sortable and it would return the rows in sorted order then the pager would break it up (post-sort) and page accordingly. The select-all feature would have to get the list of rows from the table model and then select all of the ones returned. I suppose some caching could take place or some other optimization (for example, the model could have some sort of modified event that could fire and the wrapping instance could listen for that event and invalidate its current state (or what was returned by the wrapped model). otherwise assume the rows are the same (at least according to the wrapped instance) and the old ones can still be trusted and returned.

So, for a base TableModel we need what?
1. getRows
2. getColumns
3. getDataModel
4. getHeader (allows changes in th and others…for things like dnd columns).
5. getFooter

The Rows are an array of the actual TR objects that should appear in the data (tbody) section(s) of the table. (for now only one tbody section is supported…should be able to refactor later to support getRowGroups and getColGroups instead…).

DataModel always holds all of the data for the table (even data for cols and rows not displayed) in insertion order. It will always be an array. The array may contain: arrays, hashes, or objects. The default data model will simply be a 2d array of strings. When modifying a table (adding/removing rows) the DataModel is what is manipulated. When modified it will fire a modified event…the table model will be nofitied of it and will modify its rows collection and fire a modified event of its own with the new DOMRow as a property on the event (which will travel up the chain to the JSTable object, potentially being further modified/behavior-ified along the way). The JSTable will then decide it is time to update the view (depending on the type of event (added/removed/updated) and will affect the change to the underlying dom table.

Ok…good for an up-front design/cram session. Now go do some TFD keeping this in mind as something to work toward.