On “Rolling Your Own” Large jQuery Apps
As a preface, make sure you've read my super-smart and talented yayQuery co-host Rebecca Murphey's blog post on this topic
here: On jQuery Large Applications and here: On Rolling Your Own.
Rebecca points out some huge holes in the jQuery-verse when it comes to large-application development, and gives her opinion on why she doesn't think jQuery is ever a good fit for a large application. I disagree, and she's successfully convinced me to write a post on why I think what I do, so here we are.
Also, please, no one point out that I prefer Django over Pylons, which is essentially the same argument :D . The difference, though, is that I think Pylons is awesome, and that people should totally be using it for large applications on the backend, as long as they prefer it!
First, I will start by mentioning that I have written several large applications using jQuery, and that I think that from a 'framework' perspective, something like Dojo (which Rebecca supports) or YUI3 serves as a much better core to a large application than jQuery. However, arguing that 'you shouldn't use jQuery in your large application' is an entirely different topic. jQuery does not describe or prevent any framework of application development, so you are free to choose your own to suit your needs. I do not advocate the incorrect use of jQuery as the core of your application. I do advocate JavaScript at the core of your application, though.
jQuery is a tool (lolz)
I build large applications that use jQuery. I don't build large applications on top of jQuery. This incredibly important distinction hasn't been very well clarified thus far in the conversation. I think it's a fair ambiguity, however, because while it's possible to use jQuery in well-structured ways, it's certainly the road less travelled. The 'common jquery user' tends to throw everything onto the jQuery namespace, and pull in everything as plugins, and generally very tightly couple their applications to jQuery. I think the distinction is still important for the argument, because it doesn't rule out the fact that you can write some really nice applications using jQuery.
It's not jQuery, it's you.
I think the thought that people are incapable of using jQuery in this manner stems from quite a few bad consulting experiences with companies using jQuery for no reason other than the fact that it's `the cool thing to do,` but using it entirely in an entirely backwards manner. This is also not a good way of making library decisions (at least in the long term). It doesn't reflect poorly on the code in jQuery so much as it reflects poorly on either the messaging from the jQuery team, or just the general population's inability to write good code and tendency to do what's popular. However, if Dojo were the hip-cool-designer library, they would suffer from the exact same problem.
Any library, in the hands of people who don't know what they're doing (even FuseJS), will not serve the needs of the application. This is a reality for anything that becomes popular. It's easy to like Dojo for the quality of code that comes out of it, but that's because the significantly less amount of people who use it are really good JavaScript Developers. That's important.
Being a good JavaScript developer before you start writing your application is the key to building good large applications. It's not what library you use. This is why I write about inheritance in JavaScript for the majority of my large jQuery apps articles. It's the JS people need to learn. In fact, I'd imagine there'd be some insanely backwards code from people using Dojo who didn't know what they were doing. You have to remain level-headed, though, and try to evaluate the tools without bringing in your past experiences with other developers. You can certainly choose Dojo to get away from jQuery noobs, but recommending Dojo to jQuery noobs is just bringing your problem along with you.
Roll it.
Aiight, with all that out of the way (yikes), let me give my most objective reasoning possible for why I think it's ok to use jQuery in a large app. Please keep in mind that I'm not advocating against Dojo or YUI3, I'm advocating against the absolute notion that 'jQuery should never be used for large applications.' Use what you prefer, of course.
Rebecca's core argument against rolling your own jQuery large app is that 1) no one else knows your code-base, so supporting is harder, and 2) the solutions in a library like Dojo are built to work together by smart people who have thought long and hard about the problems, and rolling your own are more fragile and can cause issues with upgrade paths and compatibility, etc. These are valid points, but I think they are painted with a narrow frame of reference for the type of app structure you might use in a large jQuery app.
It's common knowledge that a separation of concerns is key to any large application. Loose-coupling is something that I've blogged extensively about in the past. If you have a problem updating a portion of your application, it's because you wrote it too coupled. This is not unique to jQuery. Dojo's API stays about as backwards-compatible as they come (seriously), but that doesn't mean your old code will just work. In fact one of the few experiences I've had with DojoX code is that some of the less popular DojoX modules often need changes to return the correct values, or not throw errors. The core of the library, has been significantly more impressive in regards to this, but we're talking about code that you write, not the library core. I am a fan of Dojo's backwards compatibility efforts over jQuery's. Changing an API in a point release isn't always the most friendly change for devs.
Her list of requirements for a large app is well considered. It is a comprehensive list of things that often come in handy when building a large application. All of these things have been answered by smart people, in the JavaScript community. Much like her example with templating, you can decide which pieces to use (except, directly, not with library specific code...). Instead of overriding Dojo.templated you just change out the contents of your template rendering function with the new one. If you correctly loosely-coupled your application, then 'yay', you switched out a part of your app in less lines of code!
Here's the list of things that she'd expect from a framework, along with the appropriate solutions I'd consider:
- DOM manipulation tools - jQuery core
- Ajax tools - jQuery core
- A dependency management and build system - RequireJS
- Clear patterns for code organization, such as namespaced modules - The module pattern and a few object literals
- An inheritance system, preferably one that offers multiple inheritance, for sharing code across modules and staying DRY - modules +$.extend
- A non-DOM-centric, loosely coupled API for communication between modules - pub/sub || custom events
- A widget system that makes use of the inheritance system, with lifecycle management (setup/teardown) and templating - $.fn + mustache/microtemplates
- A system for maintaining templates separate from JavaScript while interning them into the build to eliminate HTTP requests - <script "text/html"> + text!requirejsdependency
- A system for abstracting RESTful server communication - assumes you want REST - but $.ajax usually works anyways...
- For a UI-intensive project, a rich widget system pluggable to arbitrary data sources and designed with an easily-extended API - jQuery UI or ExtJS on jQuery
- For an enterprise project, a11y and i18n provisions, as well as clear patterns for file organization - jQuery UI has many of these, you can also build them in. Require dictates some directory structure.
These requests are pretty obviously skewed to someone who likes working in Dojo. They are all pretty awesome ways to do things, but to say that you needed the module pattern is to entirely overlook other very valid ways of structuring complex code. Of course Dojo offers ways to do things like event-oriented programming over object-oriented. The point here is that, if Dojo has answered every question, and jQuery and friends has also answered every question (perhaps not in the same place), it's going to be just as hard to pick up the code base and figure out what's going on. I could structure my Dojo app in a way that Rebecca doesn't like, and use template overrides for template-languages that she despises, and I could tightly couple my dom elements and their attributes to my data, and it'd all be in beautiful Dojo. That Dojo has answered all the questions does not facilitate that you understood those answers or that you agree with them.
The positives
I somewhat reject the notion that using jQuery, Underscore, Require, Mustache, and the module pattern (as facilitated by Require) is "rolling your own." Sure you piece them together, by choosing how you use them, but you do the exact same thing when you choose how you use the various parts of Dojo. I think that all of these tools are as strong as the Dojo alternatives. You can argue that you could use any of these tools with Dojo because it's so flexible that you can put anything in, but then you can't argue that 'rolling your own' is bad, because that's what you just did. Either use Dojo, or agree that sometimes, it's not that bad to pull in a different way of thinking, you can't have it both ways.
jQuery normalizes things across browsers when you need it to, and serves as a mostly-fantastic way of doing dom-manip and ajax. If you use it according to it's strengths, you still can choose some really strong software alongside it that was specifically designed to be awesome at what it does.
Underscore gives you a very solid utility library, much like you'd find in Dojo, and it's extensible to boot. You can use it in two of the major paradigms natively, and it falls back to native implementations when it can. It's hardly fragile, and it's insanely easy to integrate into your project. It's no worse or better than Dojo's offering.
RequireJS is likely going to be used in Dojo 2.0 and James Burke, who wrote Require, also wrote most of the Dojo dependency management system. Require incorporates all the sweet stuff from Dojo, plus some really awesome future stuff coming from the CommonJS peeps. Some apps, though, don't require a ton of dependency management. Single page apps are likely not going to be terribly dependency heavy, and if you want... you can leave out the dependency management system all-together, and still use your modules, just like you always wanted. You can switch it out for LabJS if you want speed too.
Templating was the example that Rebecca used to show that she could roll her own templating style in Dojo. She used mustache instead of the default Dojo offering. I can't argue against that. I'm in favor of pulling together the correct tools for the job.
A lot of what is nice about Dojo, is it's prescribed format for creating modules. There's quite a bit of flexibility, but anyone who could understand the way that Dojo does this could easily understand some of the basic underlying patterns that it's enhancing. I can use object.create and the module pattern to my hearts content to structure my app, and that's not some 'wild tangent' that no one will ever be able to unravel. It's a simple, and common pattern that you'd be required to understand to use the Dojo method. Sure there's no prescribed way to exactly structure this, but that's the case with the 'extremely flexible' Dojo offering as well.
I'm not advocating creating super complex alternatives to Dojo's module structure. I think JavaScript offers a simple and flexible interface to creating and manipulating objects. I can choose which ever way I'd like. The module pattern is 2 pages of of text and code examples in The Good Parts. Just go read that.
TL;DR
Dojo is a fantastic library that I would encourage you to pick up and add to your skillset. jQuery can be a fantastic tool to use as well. "Rolling Your Own" application with good tools alongside jQuery is no harder to understand than a Dojo app, nor is it harder to support, and it's likely more specific to your needs. The fragile part of your code isn't in the tools you use, it's in the code that you write around them.
I wish we'd focus less on whether jQuery or LibX was a good or bad choice for large applications, and focus on the fact that people who don't know JavaScript are never going to write well-structured apps. Anyone who does understand the fundamental concepts behind JavaScript would be able to do it well with or without Dojo. Your language should provide your structure, and your toolkits should dictate your tools on top of that structure.
Learn JavaScript first. Then care about large apps. Then make a smart decision, according to your preferences, on which, if any, library you want to use.
-Slex
TXJS and ScriptJunkie
I have been pretty neglectful of my blog since I started at Bazaarvoice, but I think I'm going to try to pick up a little bit. That being said, here's a short update.
I am now a featured author on ScriptJunkie - a new website from Microsoft about front end development. Check out my post "Building and Maintaining Large JavaScript Applications"
I'll likely cover a few more topics concerning large application structure in the future, both on my blog and on yayQuery and ScriptJunkie.
Also, TXJS happened. I'd suggest going to the totally awesome webpage and catching the slides and the speakerrate pages for all the talks to get caught up on how much awesomeness happened. Also, my fridge is still full of left over beer, so if you're in town... beer.js at my place.
I accidentally took a Nyquil today, thinking it was Dayquil, so I'll expand on some actual fun stuff soon enough.
Thanks to all 9 of you!
<3 Alex
Superclassy Inheritance with Javascript Video
Here is the uncut director's edition of my talk given on February 20th, 2010 concerning Inheritance patterns in Javascript. Please forgive the rambling, and the bit of extra footage on either end of the talk.
Superclassy Inheritance with Javascript - Alex Sexton - NCJS 02/20/10 from yayQuery on Vimeo.
<3z
Using Inheritance Patterns to Organize Large jQuery Applications

I want to introduce/reinforce a pattern for developing large applications with jQuery. I did not invent any of this, but I find that the resources that describe this technique are few and far-between.- so I'm taking a shot at it.
By and large, when using jQuery, developers seem to forget the paradigms they learned for well structured code in other languages. This is likely due to the fact that jQuery is effectively neutral when it comes to your structural methodology or inheritance patterns, and therefore doesn't push someone in any one direction. Many times in other libraries (See Dojo Declare/Provide/Require, or MooTools Class, etc.), a paradigm is used and exclusively offered, and then code generally ends up more uniform than the oh-so-common-massive-jquery-indented-chains that I'm sure you've seen .
I'm not going to necessarily suggest that you use any single inheritance pattern, as there are many options, and each makes sense for different people and different situations. I do however suggest that you know your options. There are a few good reads on the topic of Inheritance in javascript, and I would strongly suggest people read at least a bit of the following:
- Javascript: The Good Parts (Chapter 5) -Douglas Crockford
- Prototypal Inheritance in Javascript -Douglas Crockford
- Object-Oriented Javascript -Stoyan Stefanov
- Javascript Override Patterns -Andrea Giammarchi
- Simple JavaScript Inheritance -John Resig
Choosing your form of modularity is an important step. If you come from a background of highly-classical inheritance (I learned Java in school, so...I know that world) then perhaps starting with a classical implementation is going to be your best choice. If you are trying to stay slim and do the things a little more in the "JavaScript way" (a term that means essentially nothing), then you might try to use prototypal inheritance. For my examples, any form of inheritance will at least work on most accounts.
I'll jump straight to a code example of this technique in use, and then describe it's setup and structure:
<div id="mySpeaker"></div>
Then we'll run our javascript:
$(function(){
// Call a custom plugin for your object on a dom element
$('#mySpeaker').speaker({'name': 'Alex'});
// Have quick access to the actual speaker object
var mySpeaker = $('#mySpeaker').data('speaker');
// The interface of the object that you build can
// wrap more complex dom manipulations that are
// separated from actual program logic.
mySpeaker.speak('I am a speaker.'); // Results in a dom update
// This shows automatic access to correct element in the dom
});
And the html now looks more like this:
<div id="mySpeaker"> <h1>Alex</h1> <p>I am a speaker.</p> </div>
The key here is that we didn't have to call something like $elem.append('Alex') nor did we even have to consider what would happen when a speaker object was called with the speak() function. I consider this to be the key to modular development. This level of abstraction helps keep the how and the what separated (or "loosely coupled" - if you like buzzwords). The other thing that was important to note is that after we instantiate the plugin, we have a clear two-way path between our Object and our Dom Element - both have an easy way to immediately access the other. This is important, because we often have different points of entry to jump-start a routine, so being able to access the part that you need quickly and easily is important.
Implementing this technique is pretty simple, and should actually take less brain power to set up than traversing through the dom in your head to figure out a crazy chain.
Let's start with the Speaker object.
/**
* Object Speaker
* An object representing a person who speaks.
*/
var Speaker = {
init: function(options, elem) {
// Mix in the passed in options with the default options
this.options = $.extend({},this.options,options);
// Save the element reference, both as a jQuery
// reference and a normal reference
this.elem = elem;
this.$elem = $(elem);
// Build the dom initial structure
this._build();
},
options: {
name: "No name"
},
_build: function(){
this.$elem.html('<h1>'+this.options.name+'</h1>');
},
speak: function(msg){
// You have direct access to the associated and cached jQuery element
this.$elem.append('<p>'+msg+'</p>');
}
};
I use an object literal here which puts me in the Prototypal Inheritance camp, I believe, but this is just an easily digestible pattern.
As you can see, there are easy-to-read, small functions, that have a clear purpose. In our use of this pattern, we call api type methods like speak() but not necessarily an internal method (like _build). You can hide your internal functions either by naming convention (not really hiding them), or by using something like the module pattern. In our simple example, I have just added an underscore to the beginning of the function to indicate that it's private.
Code that is organized like this is much easier to test and to change/read. This also allows you to change the way things function without changing the way that the Object api is used. For instance, we could change the speak method to alert the string instead of append it to the related element. We would have to change the internals of the speak function, but we could keep our call to it the same.
The bridge that we build is probably the most interesting part of this pattern. It's a different approach than many of the popular plugins take (slightly different than jquery ui), but it has a few really great benefits.
The most simple way to do this is by hand:
// Make sure Object.create is available in the browser (for our prototypal inheritance)
// Courtesy of Papa Crockford
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
(function($){
// Start a plugin
$.fn.speaker = function(options) {
// Don't act on absent elements -via Paul Irish's advice
if ( this.length ) {
return this.each(function(){
// Create a new speaker object via the Prototypal Object.create
var mySpeaker = Object.create(Speaker);
// Run the initialization function of the speaker
mySpeaker.init(options, this); // `this` refers to the element
// Save the instance of the speaker object in the element's data store
$.data(this, 'speaker', mySpeaker);
};
}
};
})(jQuery);
And that's it!
Now you have separated the creation of the plugin from the actual code itself. You are using the plugin to attach objects (with any inheritance patten) to dom elements and visa versa, but the plugin itself is just the connection and initialization code. This means that we could generalize this process further. I first saw this from Scott Gonzalez (of the jQuery UI team) and his code later became the 'widget factory' in jQuery UI. I prefer to not pass strings into my plugins in order to call functions, but it's a valid approach as some people would take issue with having to pull out the object each time they started with a dom element.
Here is some code that might get you started writing/using a 'bridge' function (bridge is what's found now in jQuery UI 1.8) that can help you attach your general code with a given plugin (since writing that same initialization plugin code multiple times would get old and defeat the whole DRY principle that our inheritance model has hopefully provided). This code is mostly courtesy of Scott Gonzalez because I couldn't think of a more stripped down elegant approach to this. I changed it to accept Objects instead of Constructor Functions because that works a little better with my example (prototypal inheritance). I also force it to call my init function in order to save myself an extra call. (This example shows Scott's use of this method along with John Resig's Simple-Inheritance implementation - also very cool.)
$.plugin = function(name, object) {
$.fn[name] = function(options) {
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
var instance = $.data(this, name);
if (instance) {
instance[options].apply(instance, args);
} else {
instance = $.data(this, name, Object.create(object).init(options, this));
}
});
};
};
// With the Speaker object, we could essentially do this:
$.plugin('speaker', Speaker);
// At this point we could do the following
$('#myDiv').speaker({name: "Alex"});
That's about all there is to it. I'd encourage you to pick some pattern for your development that isn't just inline chaining of jQuery function calls. This way of breaking up and organizing functionality in your code serves as a quick and easy jumping-off point for testing and modularity. It's much easier to test the individual functions of a modular object than it is to write tests for a single-line chain of jQuery calls.
Also, I do get some feedback along the lines of "well, my code is not a plugin" - "this isn't applicable to my code" - but I usually tend to disagree. The stigma that a jQuery plugin has to be for general consumption is flawed. I encourage you to use the plugin architecture if you are creating functionality based on a dom element selection. For instance, if you are adding an error notification system, it would be very easy to create a notification object that attaches to a div and has the methods required for notification directly attached to it, rather than having a function that merely hides and shows random dom elements.
I am doing a round up of performance on a lot of this inheritance usage and I should get to writing another entry on that soon, but from my early tests, using reasonable inheritance is generally not that expensive. If you are pushing the limits of CPUs and browser rendering, you might have to make some sacrifices, but for the general case, the instantiation hit of inherited objects is probably well worth your while.
I'd love to hear about the way you approach this problem.
Superclassy Inheritance in JavaScript Developer Day Talk Slides
I thought I would make a quick post for anyone coming here for my slides from Developer-Day here in Austin.
I plan on giving a screencast of sorts a try, and perhaps even breaking up some of the sections into a few blog posts on the subject. Encapsulation, modularity and code reuse is an interesting topic in any language, but especially when it comes to applying those ideas to real life applications and web sites.
The demo pages can be found at A Totally Realistic Demo Page for applying Inheritance in Javascript or whatever.
Thanks to Viget for having me out to speak today, it was a blast.
Invalid JSON in jQuery 1.4 and beyond
I'm pretty happy about jQuery's move to only supporting valid JSON, as well as it's standardization across browsers to enforce that rule, even if native JSON parsing isn't being used. I think it's silly for people to expect things to work when they are passing invalid data back and forth. Much like no one would dare write invalid xml documents for data transfer, the same should be applied to the JSON data format. Simply put, if you aren't conforming to the JSON Standards as defined on http://json.org/ - then you aren't using JSON. You are just passing Javascript source-code back and forth. I wouldn't suggest it.
Now, I understand there are a variety of libraries and services that currently break the standard. I would strongly suggest you write to them and demand that they follow the spec. Nothing should break for their users, so it's not much too ask. Until then I wrote this little lovely plugin so you could consume criminal data sources until they get their acts together:
jQuery.getInvalidJSON = function(url, data, callback) {
return jQuery.get(url, data, function(d){
callback.call(this, (new Function('return ' + d))());
}, "text");
};
This is just an unsafe eval of Javascript source that is unwisely used as a data exchange format. I don't think it belongs in jQuery, but if you are of the unlucky few that are forced to receive invalid JSON don't let it stop you from upgrading to 1.4.
<3z
Don’t let document ready slow you down.
I just wanted to quickly post about a common performance hit that I see in pages (including a bit of my old stuff), especially ones that load data on page load.
A common pattern for application development loads a page template with the application code included and then makes an asynchronous data request to load all the relevant data.
One example might be something like:
<html>
<head>
<script type="text/javascript" src="jquery.js" />
<script type="text/javascript">
$(document).ready(function(){
// make an ajax request once the dom is ready
$.ajax({
url: 'ajax.php',
success: function(data) {
for(var i in data) {
$('.app-container').append('<div>'+data[i]+'</div>');
}
}
});
});
</script>
</head>
<body class="app-container">
// Perhaps a very large dom - which makes the page load slower
</body>
</html>
The problem with this is that the request for the page content isn't made until the dom is ready, but that request doesn't require the dom at all.
Instead of wrapping the $.ajax() call in a dom ready function, try just wrapping your `success` callback function in one instead. This will allow the request to fire off as soon as possible, but will ensure the handling of the data doesn't happen until your domready event has fired.
<html>
<head>
<script type="text/javascript" src="jquery.js" />
<script type="text/javascript">
// make an ajax request right away
$.ajax({
url: 'ajax.php',
success: function(data) {
$(document).ready(function(){ //<-- Hey Guys check this out!
for(var i in data) {
$('.app-container').append('<div>'+data[i]+'</div>');
};
});
}
});
</script>
</head>
<body class="app-container">
// Perhaps a very large dom - which makes the page load slower
</body>
</html>
This should speed up the load time of your page. From my testing, there doesn't seem to be any issues with this, so I believe it's safe to use. The function will fire immediately if your domready event has already fired, and it will wait to fire if the dom isn't ready yet. You can have as many document ready calls as you want on your page without overwriting old ones, so don't worry about only defining it in one place. I would also imagine that you wouldn't need too many more than two or three if you structured your code in an intelligent way.
---
As a footnote, this is only one of many things you can do outside of dom ready to help speed up the execution of your code. If you are binding events with 'live' or if you are just defining functions, I'd suggest that you do it inside of a closure instead of inside of a dom ready function. Then put just the stuff you need to run with the dom into the dom ready function.
The reason for this is essentially the same as before. You can allocate all the function definitions and variables while the page is building, rather than afterwards. Anything that you can do asynchronously right away is going to generally be better than waiting until the document is ready. There are a few ways to make this a little better organized, but organization isn't the topic, so here is a simple example of code you might write with minimal code execution in the dom ready function. The closure that I have surrounding the entire block of code serves to make the variables have a similar scope affect as it would inside of a document ready function, though it's not absolutely necessary.
(function($){ //<-- use a closure to protect your namespace and your `$`
// This runs immediately
$('a').live('click', function(e){
alert('OKBYE!');
return true;
});
// define functions outside of the dom ready
function doSomething(input) {
$('div.something').do(input);
// you can even use functions that require the
// dom inside of a defined function as long
// as you don't call it until the dom is ready
$('div.somethingelse').click(function(){
console.log("I don't need no dom ready");
});
}
// dom ready
$(document).ready(function(){
// Do stuff that requires the dom, and
// use your functions from outside
$('a.special').click(function(e){
doSomething('special');
});
// yay!
});
})(jQuery);
It's nothing revolutionary, but I figured I'd get it out there!
yayQuery Podcast 1.0
A few of the ladies and fellas from the #jquery IRC (Adam J. Sontag, Paul Irish, & Rebecca Murphey) and I decided to make a podcast on the topic of jQuery. We landed on the name yayQuery!
From Paul's blog post:
---------
We talk about...
- Underscore.js - a great utility belt (very handy for Ruby/Python folks), comes with John Resig's microtemplating script and lots more
- Thickbox - Rest in peace. Also alternatives: Colorbox, jQuery UI Dialog
- jQuery on mobile. Phonegap, XUI, jQTouch, going it alone
- Anti-Pattern of the week: css(key,val)
- $var and Hungarian notation
- ... and dancing
If you'd like a download:
mp3 audio (30mb), mp4 video (94mb), ogg video (61mb)
---------
I'd love to get your feedback on what you liked or didn't like. If people seem to enjoy it, we'd love to step up the production just a bit, but it doesn't really make sense quite yet.
You can also follow us on twitter (@yayQuery) if you want updates for the next episodes and such. Yay!
Goto.js
Today I launched my new site www.summerofgoto.com. It is the official new homepage for my new script Goto.js. Goto.js adds the functionality of the goto command into native javascript. It uses James Padolsey's parseScripts as a preparser and rewrites the input code to be valid javascript. Leave it to me to write programs solely for the comedic value, but I actually did find some interest in the fact that it is challenging to implement functionality that is so basic to low level programming.
The script (which can be downloaded at the site) hinges on a single heuristic for implementing Goto. In javascript, while loops can have labels, and they can also have 'continue' statements that accept a label as the parameter.
e.g.
label1: while (i < 10) {
if (!valid(i)) {
continue label1;
}
i++;
}
In effect, this is just a crappy goto statement that is confined to a special case. So my goal in goto.js was to extend this case to all cases. I did this by surrounding everything after a label with a while loop that only runs once by default. The only tricky part being that while loops cannot stretch across multiple functions or blocks. So each while loop ends at the end of its block scope, not the file or script. This is an interesting problem, because typically, when goto was around and actually heavily used, there weren't a whole lot of functions being written. Even if I was somehow able to allow you to start running code from the middle of a function from the middle of a different function, I don't think it would work, because the context of all the variables that have been passed into the new function cannot be guaranteed to exist.
The only feature that I am actively toying with currently is a way to allow goto satements to jump to labels that haven't been declared yet. After reading a bit on the subject, different languages had different rules about this feature in the past, and some languages therefore also did/do not support forward looking goto statements.
Enjoy the Summer of Goto!
P.S. For anyone who is wondering (so far a total of zero people), Summer of Goto is a term that was popularized by Paul Irish, while discussing this script and PHP's decision to add goto into their language.
And for those who do not immediately recognize that this entire thing is a joke, please forgive me. <--(insurance).
Class Blog:
Hello all,
I don't expect a terribly large readership, but hopefully I can post some things that will help some people along the way. This will be less of a personal endeavor and more of a location for me to write about some of the things that I create or think are cool in my areas of interest.
:)