Tuesday, November 18th, 2008
Category: JavaScript

Because viewing the source is too bothersome, we now have WTFramework (short for “What The Framework”, obviously), a bookmarklet that will detect and display the Ajax / JavaScript frameworks used in the current website.
It does so by checking for loaded JavaScript objects for each framework, not by analyzing the <script> element URIs.
Handy.
Category: JavaScript
We posted on reglib, the new declarative event based library by Greg Reimer. I was a little confused at first, but Greg has posted a follow up which includes a demonstration comparing reglib to jQuery that makes his strategy a lot clearer:
Let me first of all stress that I’m not trying to bust on JQuery here. JQuery does something that needs to be done, and it does it just about as well as can be done given the tool-set browsers have collectively placed at our disposal.
With that said, I’m going to go ahead and pimp the reglib way of doing things, by which I mean declarative, over the load-traverse-modify methodology, which JQuery makes so easy.
The demo page linked below has two identical interactive widgets; one wired up using JQuery, and the other wired up using reglib.
The page is rigged like a science experiment, with a control followed by several tests in which you observe differences in behavior between the two widgets in response to various stimuli. The goal is to demonstrate reglib’s resilience under duress (as it were). Enjoy.
The tests show:
The JQuery widget has been cloned using the DOM clone() method. After closing this message, note how the cloned version is non-functional. This is because event behavior needs to be explicitly re-added to each new element under the load-traverse-modify methodology.
The reglib widget has been cloned using the DOM clone() method. After closing this message, note how the cloned version functions normally since reglib event declarations automatically affect all additions to the DOM.
The DOM has been completely overwritten by: document.body.innerHTML += ''; After closing this message, note how none of the JQuery widgets work anymore, meanwhile the reglib widgets continue to function as normal.
At the end of this page’s HTML source is a comment containing a huge block of random numbers. If you don’t have a fast internet connection and you SHIFT+RELOAD this page, it will simulate network latency and/or or dynamic page processing delays, which cause a delay before the load event fires. After closing this message, SHIFT+RELOAD the page. While the page is yellow it means the load event hasn’t fired. During this time, note how the JQuery widget is non-functional, but the reglib widget is functional. This may not be apparent if you have a fast internet connection.

Monday, November 17th, 2008
Category: JavaScript
Erik Arvidsson has an updated take on instance private, class private, package and friends.
One thing that shoots out at you is actually at the end:
Gmail was written without any true private members. We just use a naming convention.
We love to focus on little geek things like encapsulation, but once again... you can write amazing, complex applications without purity.
In his post, Erik talks about the various issues around getting privacy and how closure magic can be "very memory hungry since every instance needs its own function to encapsulate the local vars."
He then walks through ideas on getting the best of both worlds (private but performant) and ends up with a version you can try that even allows you C++ "friends" semantics:
JAVASCRIPT:
-
-
var A;
-
(function() {
-
var KEY = {};
-
A = ...;
-
-
var friendKeys = {};
-
A.addFriend = function(id, key) {
-
friendKeys[id] = key;
-
};
-
-
function getFriendPrivate(obj, id) {
-
return obj._getPrivateWithKey(friendKeys[id]);
-
}
-
-
A.prototype.accessFriendPrivate = function(obj) {
-
return getFriendPrivate(obj).b;
-
};
-
})();
-
-
var B;
-
(function() {
-
var KEY = {};
-
B = ...;
-
A.addFriend('B', KEY);
-
})();
-
Yet, after all that, he still doesn't think you should use it :)
Friday, November 14th, 2008
Category: JavaScript
, Library
, Tip
Our own Michael Mahemoff is at it again, creating a simple little GUID generator called Guid0:
Guid0 is a GUID library for Javascript. Okay, it doesn't yet do official, bona fide, 128-bit, GUIDs yet, mainly for API design reasons. But this is a library you might find useful if you want to generate a unique ID in your Ajax app.
JAVASCRIPT:
-
-
// simple
-
guid = new Guid();
-
var newguid = guid.generate();
-
-
// options
-
guid = new Guid(
-
{
-
chars: Guid.constants.base85, // or you could say "abc" if you only wanted those chars to appear
-
epoch: "June 1, 2003",
-
counterSequenceLength: 2, // a counter field appended to the end
-
randomSequenceLength: 2 // a random field appended to the end
-
}
-
);
-
He is working on 128-bit support.
Thursday, November 13th, 2008
Category: JavaScript
, Performance
This is officially the week of John. If he delivers top notch posts for the rest of the week he wins an Ajaxian award or something. Maybe we need to bring back the "pack of cards" where each card is an Ajax personality and John gets to be Ace of Hearts or something.
I remember talking with some of the V8 team about how poor the world of timing is. Chrome is a lot more accurate in its timing, which can do it a disservice in browser performance tests. Some browsers would respond with "0" when Chrome would return "0.001" and it would hence suffer.
Add that to the flawed "just add up the total time for all tests" mentality of some tests and you end up with very skewed results (you could do amazingly bad on one test that in practice never matters and really well on the others, but it all evens out).
Here comes John with a post on the accuracy of JavaScript timing which came out of a bad situation:
I was running some performance tests, on Internet Explorer, in the SlickSpeed selector test suite and noticed the result times drastically fluctuating. When trying to figure out if changes that you've made are beneficial, or not, it's incredibly difficult to have the times constantly shifting by 15 - 60ms every page reload.
This lead him to tests life on various browsers and operating systems and he put up the raw data for you to check out.
He concludes:
Testing JavaScript performance on Windows XP and Vista is a crapshoot, at best. With the system times constantly being rounded down to the last queried time (each about 15ms apart) the quality of performance results is seriously compromised. Dramatically improved performance test suites are going to be needed in order to filter out these impurities, going forward.

Monday, November 10th, 2008
Category: Examples
, JSON
, JavaScript
, Yahoo!
BOSS - Build Your Own Search Service (the your is silent for reasons I cannot tell you as it would endanger the lives of our agents in the field) is a Yahoo! API to access their search index and get the data back either as XML or JSON. Whilst there is ample documentation available it can still be a bit daunting to use the API purely in JavaScript - especially when you want to have several asynchronous calls - for example when you want to search the images, news and web sites for a certain query.
I've had several complaints of Hackers at the Open Hack Day in Brazil about this and wanted to make their lives easier by writing a wrapper for the API.
This wrapper is yboss and it was a big success at the Hack Day with the winning hack in the BOSS category actually being based on it.
To use the wrapper all you need to do is to embed it in your document
HTML:
-
-
<script type="text/javascript" src="yboss-lib.js"></script>
Then you have access to the get method of the wrapper which searches all the defined search options with the query you provided. You can define a callback method that will be called when all searches have been successfully performed.
JAVASCRIPT:
-
YBOSS.get(
-
{
-
searches:'search,images,news',
-
query:'obama',
-
count:10,
-
callback:seeddata
-
}
-
);
-
function seeddata(o){
-
var all = '<h4>Web Sites</h4>' + o.webHTML +
-
'<h4>News</h4>' + o.newsHTML +
-
'<h4>Images</h4>' + o.imagesHTML;
-
var out = document.getElementById('results');
-
out.innerHTML = all;
-
}
The data is provided either as a JSON object with all the mandatory properties for a BOSS result display or - as shown here - as HTML lists that can be written out via innerHTML.
Friday, November 7th, 2008
Category: JavaScript
We've seen the community do a lot with <canvas> over the past few months, and every so often it's fun to see the good ol' <div> approach to graphics and animation.
Tavs Dokkedahl gives us a good one of those with his JavaScript Graph Plotting Tool:

As part of a larger animation framework I have created a plotting tool for
visualizing functions. It is made entirely in JavaScript, uses no graphics
and the generated source code is W3C compliant.
The first beta is ready for public viewing (and hopefully feedback) and
currently supports
Real valued functions of one variable y = f(x)
Parameter functions for plane curves (x,y) = f(t)
Customizable plots like curve resolution and axis positioning.
Simple zoom functionality (not for plane curves)
It's actually a pretty cool little cross-browser app.
Tuesday, November 4th, 2008
Category: JavaScript
, Testing
, Unobtrusive JS
By now, most developers have (or should have) come to realize how important it is to build unobtrusive JavaScript code. Apart from ensuring a better user experience, today's tools and libraries make it extremely easier to embrace this practice.
Continuing down the path of providing developers good tools, Robert Nyman of DOMAssistant fame has updated his Obtrusive JavaScript Checker. The tool comes in a couple of different forms including a GreaseMonkey script, a Firefox add-on and newly included, a command for use with Mozilla's Ubiquity Firefox add-on.
One common and tedious task when improving code is to find inline events in the HTML code, and make sure they are implemented in an unobtrusive fashion instead (more about unobtrusive JavaScript). The web is riddled with inline events, and I strive to make it a better place. :-)

The Obtrusive JavaScript Checker tool traverses through all elements in a web page, and when it finds a HTML element with inline events, it highlights it with a red border. The newest release now offers support for "javascript:" links as well as much greater detail about the element when you hover over it. In addition, a new report summarizes the number of javascript: links and inline events in the current web page as well as the number of occurrences of each type of inline event.
Link to Robert's updated Firefox add-on: https://addons.mozilla.org/en-US/firefox/addon/9505
Thursday, October 30th, 2008
Category: Framework
, JavaScript

Mikael Bergkvist has created Widgetplus, a gadget platform. He told us about it.
XML Runtime
The structure of an application is defined in XML.
It’s loaded into the serverside runtime like this: javascript:xin.app(' http://www.naltabyte.se/desktop/xin/demo/programs/basics.xml ');
We get this as a result. (the ‘test this’ link)
Changes to the app remain persistent because on the server, the xml object has changed.
Of course, different users gets different versions of the same widget, because they have their own xml runtimes.
A widget can contain any amount of javascript to execute clientside, and also include any css to style it, like this calendar application.
A widget can also split itself into subsets, this example opens a new widget as a dialog, which is really a part of the same widget, and saves data back to itself from it.
XML objects can access each other on the server within the boundaries of the same account.
It means that widgets can access other widgets and send/recieve data from them.
Data can also be sent / retrieved cross domain, without opening the widget on the client at all.
The xml for this app in this example, which is behaving much like a webservice, is here.
File system access
Widgetplus allows complete filesystem access for a widget, but only within the user account.
By default, widgets always access the demo account, but when logged in, they access the users home account, it’s files and folders, and other settings.
This is crossdomain by default, like this example on Blogger, which accesses all files on the demo account.
There are several more ways this can play out:
The API lets anyone build their own solutions/variations of this.
Conclusion
These two parts, together, define what widgetplus is.
It’s a serverside xml runtime for widgets, which can access and manipulate files and folders that belong to the free user account.
Users can always sign up / log in to any widget (by default), the developer wont have to bother about that.
Widgetplus clones all widgets as soon as someone signs up, and also automatically creates a webspace directory for the new user with the default folders in place.
Otherwise, whenever someone logs in, it simply serves the requested xml object(s) associated with that user.
It’s important to note that widgetplus isn’t a BOX.net service, the webspace is for widgets - and whatever they do with it – it’s not for uploading your entire music collection. We will move to a server network in about two months, after which we plan to offer unlimited file storage, but for now, we need to keep a tight leach.
Tuesday, October 28th, 2008
Category: JavaScript
, Library
Peter Michaux has shared how he structures his code these days, as he has settled on a pattern:
The code example below is a simple little logger widget. It appends messages to a list and has a clear link to delete all the recorded messages.
JAVASCRIPT:
-
-
// Wrap code with module pattern.
-
(function() {
-
var global = this;
-
-
// helper functions
-
var sanatize = function(msg) {
-
return (String(msg)).replace('&', '&').replace('<', '<').replace('>', '>');
-
};
-
-
// widget constructor function
-
global.MY_makeLogger = function() {
-
-
// private instance methods
-
var clear = function() {
-
LIB_emptyElement(logEl);
-
};
-
var append = function(msg, className) {
-
LIB_insertBottom(logEl,
-
'<dt class="'+className+'">' + (new Date()) + '</dt>' +
-
'<dd class="'+className+'">' + sanatize(msg) + '</dd>');
-
};
-
-
// create widget DOM fragment
-
var parser = document.createElement('div');
-
LIB_upateElement(parser,
-
'<div class="Logger">' +
-
'<p><a href="#" class="clearLink">clear</a></p>' +
-
'<dl class="log"></dl>' +
-
'</div>');
-
-
// find pieces and enliven DOM fragment
-
var rootEl = LIB_find('.Logger', parser)[0];
-
parser = null; // enable garbage collection of parser div
-
var logEl = LIB_find('.log', rootEl)[0];
-
LIB_on(LIB_find('.clearLink', rootEl), 'click', function(e) {
-
LIB_preventDefault(e);
-
clear();
-
});
-
-
// public instance methods
-
return {
-
getRootEl: function() {return rootEl;},
-
log : function(msg) {append(msg, 'log' );},
-
warn : function(msg) {append(msg, 'warn' );},
-
error : function(msg) {append(msg, 'error');}
-
};
-
-
};
-
})();
-
He talks about how he uses naming conventions to keep track of library functions, exported functions, gensym ids.
Category: JavaScript
, Performance
Matt has a nice post on delaying JavaScript execution in a way that waits for certain events to finish:
If you're looking to execute javascript code whenever someone finishes (or stops temporary) scrolling, moving the mouse, or resizing the page, you may find the following segment of code useful.
He shares the following boilerplate code:
JAVASCRIPT:
-
-
var onFooEndFunc = function() {
-
var delay = 50; /* milliseconds - vary as desired */
-
var executionTimer;
-
-
return function() {
-
if (executionTimer) {
-
clearTimeout(executionTimer);
-
}
-
-
executionTimer = setTimeout(function() {
-
// YOUR CODE HERE
-
}, delay);
-
};
-
}();
-
This can be useful in a variety of ways, but it got me thinking about having the ability