Adding Axis Titles to DojoX Charts

DojoX charting is a very powerful 2D graphics charting solution that works cross-browser. One thing that is an often requested feature is axis titles. I’ve come up with a solution (inspired by a post on the old Dojo forums) that leverages the current API and renders correctly in all browsers. I’ll be using Dojo 1.5 from Google’s CDN plus a local module as I outlined in my local module with a CDN build tutorial.

my/Chart2D.js

dojo.provide("my.Chart2D");
 
dojo.require("dojox.charting.Chart2D");
 
dojo.declare("my.Chart2D", dojox.charting.Chart2D, {
	render: function(){
		this.inherited(arguments);
		var axes = this.axes,
			theme_tick = this.theme.axis.tick,
			theme_font = theme_tick.font,
			theme_font_color = theme_tick.fontColor,
			dim = this.dim,
			offsets = this.offsets,
			x_middle = (dim.width / 2) + (offsets.l / 2),
			y_middle = (dim.height / 2) - (offsets.b / 2),
			m = dojox.gfx.matrix;
 
		// For each axis defined, loop through, check if there
		// is a 'title' property defined.
		for(var i in axes){
			var axis = axes[i];
			if(axis.opt.title){
				var x, y,
					rotate = 0;
 
				// If the axis is vertical, rotate it
				if(axis.vertical){
					rotate = 270;
					y = y_middle;
					x = 12;
				}else{
					x = x_middle;
					y = dim.height - 2;
				}
 
				// Render the text in the middle of the chart
				var elem = axis.group.createText({
					x: x_middle,
					y: y_middle,
					text: axis.opt.title,
					align: 'middle'
				});
 
				// Set the font and font color
				elem.setFont(
					axis.opt.font || theme_font
				).setFill(
					axis.opt.fontColor || theme_font_color
				);
 
				// If the axis is vertical, rotate and move into position,
				// otherwise just move into position.
				if(rotate){
					elem.setTransform([
						m.rotategAt(rotate, x_middle, y_middle),
						m.translate(0, x - x_middle)
					]);
				}else{
					elem.setTransform(m.translate(0, y - y_middle))
				}
			}
		}
	}
});

This is pretty straight-forward: the code figures out where the middle of the axes are and places the title there, rotating if necessary. I’ll point out one important part: the text must initially be created in the middle of the chart and then translated into position. If the text is created where it should be placed, WebKit-based browsers will hide the vertical axis’ title because it initially renders partially off-screen.

You use this new class exactly like you would use dojox.charting.Chart2D, except that each axis can now be passed a title attribute:

new my.Chart2D('chartNode').
	setTheme(dojox.charting.themes.PlotKit.cyan).
	addPlot("default", {
		type: "Default",
		lines: true,
		markers: true,
		tension: 2
	}).
	addAxis("x", {
		title: 'X Axis',
		min: 0,
		max: 6,
		majorTick: { stroke: "black", length: 3 },
		minorTick: { stroke: "gray", length: 3 }
	}).
	addAxis("y", {
		title: 'Y Axis',
		vertical: true,
		min: 0,
		max: 10,
		majorTick: { stroke: "black", length: 3 },
		minorTick: { stroke: "gray", length: 3 }
	}).
	addSeries("Series A", [
		{ x: 0.5, y: 5 },
		{ x: 1.5, y: 1.5 },
		{ x: 2, y: 9 },
		{ x: 5, y: 0.3 }
	]).
	addSeries("Series B", [
		{ x: 0.3, y: 8 },
		{ x: 4, y: 6 },
		{ x: 5.5, y: 2 }
	]).
	render();

Chart with axis titles

I’ve posted a live example, a tarball, and a zip file for download. As you can see, DojoX charting is quite powerful on its own but is easily extensible.

Using Local Modules With a Cross-Domain Dojo Build

Lately, I have been using Dojo from a CDN as much as possible. There are several reasons to use a cross-domain build of Dojo that are listed here:

  1. You get more connections in MSIE, since you can load from another domain. Faster loading.
  2. You get increased cacheability/startup if many of your applications use the same installation.
  3. Resource loading does not block the rest of the page from filling in as with Dojo’s normal, synchronous loading.
  4. With a local install, your ISP may otherwise charge you for all of those Dojo bits that you are serving.

The one problem with using a CDN is that you don’t have control over the build, which means you can’t build custom code into it. Building custom code into a build is what most people do with builds, so it would seem you can’t develop code using Dojo’s module system against a CDN. This couldn’t be farther from the truth.

In this post, we’re going to be using Dojo from AOL’s CDN. This method can also be used against a custom cross-domain build. It may not seem like that would be very useful, but you may need to develop a new custom module against your build and don’t want to rebuild to test each change you make. Let’s look at the source:

xdlocal.html

<!DOCTYPE HTML>
<html>
<head>
	<title>XDomain Build With Local Modules</title>
	<style type="text/css">
		@import "http://o.aolcdn.com/dojo/1.4.3/dijit/themes/tundra/tundra.css";
	</style>
	<script type="text/javascript">
		var djConfig = {
			isDebug: true,
			parseOnLoad: true,
			baseUrl: './',
			modulePaths: {
				'my': 'my'
			}
		};
	</script>
	<script type="text/javascript" src="http://o.aolcdn.com/dojo/1.4.3/dojo/dojo.xd.js"></script>
	<script type="text/javascript">
		dojo.require("my.Foo");
	</script>
</head>
<body class="tundra">
	<button dojoType="my.Foo">
		This is a "my.Foo" button.
	</button>
</body>
</html>

my/Foo.js

dojo.provide("my.Foo");
 
dojo.require("dijit.form.Button");
 
dojo.declare("my.Foo", dijit.form.Button, {
	onClick: function(){
		alert('Button clicked!!');
	}
});

I have also provided a live example as well to show it working. You can grab the source files in a tarball or zip file as well so you can play around with it.

The key part here is in the HTML file:

<script type="text/javascript">
	var djConfig = {
		isDebug: true,
		parseOnLoad: true,
		baseUrl: './',
		modulePaths: {
			'my': 'my'
		}
	};
</script>
<script type="text/javascript" src="http://o.aolcdn.com/dojo/1.4.3/dojo/dojo.xd.js"></script>

djConfig is used to configure Dojo upon loading. The modulePaths object tells where to find the modules relative to baseUrl. Changing baseUrl does not affect the URL used for dojo, dijit, or dojox because those are hard-coded in the cross-domain build. The main thing to remember is that baseUrl must end in a /. Given this information, we can deduce that I am telling Dojo that the my modules can be found at http://www.reigndropsfall.net/demos/xdlocal/my/.

As you can see from this simple example, Dojo’s module system is very versatile. Not only can you host a build, host a custom build, host a cross-domain build, or use a CDN, but you can combine cross-domain builds with local modules which can save time and bandwidth costs.

Monkey patching

Recently, David Walsh tweeted that I had schooled him. I received several questions about what I had schooled him in, so I decided to blog about it.

David was trying to change the behavior of a method of a widget on a page, but for all instances of that widget rather than just one instance. What follows is a lesson on monkey patching. I’m sure there are other tutorials out there about it, but this is more for my sanity (and to get David off my back about blogging) than anything else.

Wikipedia defines Monkey patching as “a way to extend or modify the runtime code of dynamic languages (e.g. Smalltalk, JavaScript, Objective-C, Ruby, Perl, Python, Groovy, etc.) without altering the original source code.” For our purposes, we’ll only be looking at JavaScript. Wikipedia also lists four uses for monkey patching:

  • Replace methods/attributes/functions at runtime.
  • Modify/extend behavior of a third-party product without maintaining a private copy of the source code.
  • Apply a patch at runtime to the objects in memory, instead of the source code on disk.
  • Distribute security or behavioral fixes that live alongside the original source code.

In the JavaScript world, monkey patching can be very important if you’re using a third-party library. This is especially true if you are using it from a CDN or are checking it out from a version control system. We’ll use this HTML as our test page and use Dojo from the AOL CDN:

< !DOCTYPE HTML>
<html>
<head>
	<title>A Monkey-patching example</title>
	<script type="text/javascript" src="http://o.aolcdn.com/dojo/1.4.3/dojo/dojo.js"></script>
	<script type="text/javascript">
		dojo.ready(function(){
			dojo.declare("Adder", null, {
				constructor: function(base){
					this._base = base;
				},
 
				add: function(what){
					return this._base + what;
				}
			});
		});
	</script>
</head>
<body>
</body>
</html>

I will assume basic knowledge of JavaScript, object prototype chains, and dojo.declare. The code examples that follow can be pasted into your browser’s JavaScript console (such as Firebug).

Monkey patching object instances

Let’s say you have an Adder instance and you’d like to change the calculation that happens when calling add(). Simply add an add method to the object instance:

var myAdder = new Adder(5);
myAdder.add(5); // returns 10
myAdder.add = function(what){
	return what + 20;
};
myAdder.add(5); // returns 25

That’s all well and good, but how do we perform the original add calculation, yet modify it without rewriting the method completely? Just store the add method to a variable, add an add method to the object instance, and call the stored add method within the new add method. You’ll generally also want to wrap that all in a closure so only the new method can access the old method. Confused yet? Don’t be:

var myAdder2 = new Adder(5);
myAdder2.add(5); // returns 10
(function(){
	var oldAdd = myAdder2.add;
	myAdder2.add = function(what){
		return oldAdd.call(this, what) + 20;
	};
})();
myAdder2.add(5); // returns 30

One note

You might have noticed that I didn’t use the word “overwrite” when talking about monkey patching object instances. This is because object instances look up their properties from their prototype unless explicitly defined on them (like _base). This is what one might call “masking” and is an important concept in JavaScript. When we were monkey patching before, we were actually masking the add method on the Adder prototype (it’s a subtle difference, but important).

Monkey patching an object’s prototype

Great! We can modify individual instances. But let’s say we have 30 Adder instances and we don’t want to modify them all every time. This is where monkey patching the prototype comes in:

var myAdder3 = new Adder(5);
myAdder3.add(5); // returns 10
Adder.prototype.add = function(what){
	return this._base + what + 10;
};
myAdder3.add(5); // returns 20

Here, we’re overwriting (instead of masking) the add method. This applies to instances already created that haven’t had their methods masked (try myAdder.add(5); and myAdder2.add(5);) and future created instances. As we did before, you can also call the originally defined method:

var myAdder4 = new Adder(5);
myAdder4.add(5); // returns 20
(function(){
	var oldAdd = Adder.prototype.add;
	Adder.prototype.add = function(what){
		return oldAdd.call(this, what) + 10;
	};
})();
myAdder4.add(5); // returns 30
myAdder3.add(5); // returns 30

Note how myAdder3 is also affected by this new monkey patch. As you can see, monkey patching is quite simple yet very powerful. Although I used dojo.declare, this can be used to modify any JavaScript object or prototype chain: you can modify a widget’s behavior, add debugging output to a method, or even modify arguments passed to the original function.

Update on life

Man, I keep telling myself I’ll write more often, and then I go a month or so without writing… what is my problem? Let me catch you guys up with what’s happening.

Work
After a year and a half at Master Packing and Rubber Company, I’m leaving my position there to join the gang over at SitePen full time working on Dojo and other DHTML/JavaScript web application “stuff”. My last day at MPRC is this Friday and I start at SitePen a week from today. I’ll still be working on MPRC’s website in my free time and offering them a bit of technical support every once and a while (read: over the next month, I’ll be getting phone calls left and right from them). It’s been a fun year and a half and I’ve learned a ton about business, quality assurance, and website administration and I truly appreciate them giving me the opportunity to work for them. That being said, I’m really looking forward to working from home for SitePen and working full time with the some of the best in DHTML and JavaScript.

Dojo
We’re approaching our 0.4 release and there are plenty of treats for this release! One of the biggest developments for this release is the gfx package. Gfx is an SVG drawing API that works in both IE and Firefox. Check out the clock demo. Another SVG goodie we’re packing into this release is the charting engine. These goodies are thanks to the wonderful work of Eugene Lazutkin, Tom Trenka, Gavin Doherty, and Kun Xi.

Capoeira
Last Wenesday, my wife took some (over 200) pictures at our capoeira class of our capoeira family. I’ve posted them here. She started taking pictures during aú and handstand exercises, took them throughout the roda, and ended the excursion at Thai Flavors (our hangout after Wednesday night practice).

And life keeps flying by

It’s been almost a month and a half and my blogging has been quite absent. Here’s what has been happening…

Life
Our trip to San Jose (last month) went great. We had 4 days to bum around Silicon Valley and the surrounding areas. Since this was a vacation, we decided not to do too much and really only did one touristy thing: we went down to Carmel and 17 mile drive for a day. It was fun and it was a really beautiful area. And the driving out there wasn’t too bad. The Dojo Developer Day (which is what I went out there for in the first place) went great as well.

Dojo
Dojo has been taking off recently. Last month, we released 0.3.0 and about a week ago we released 0.3.1. For the 0.3.0 release, I refactored/rewrote the effects portion, James Burke wrote a cross-domain loader, Tom Trenka added a Google and Yahoo! maps interface, and Torrey Rice added the new widget theme. There was more, but those are the ones that stick out in my mind. We had about 50k downloads in the month that 0.3.0 was out. For 0.3.1, the cross-domain loading has been improved and we have a cross-domain package now, plus AOL is now hosting Dojo on their CDN, IBM is actively helping with a11y, and Sun just announced they are going to start developing widgets for Dojo. All-in-all, it’s been a good month.

My current endeavors

Ok, so I said I would keep up with this blogging thing, but I’m not doing a very good job. It’s been over two months since I last blogged. What the heck is my problem? So here’s the run-down of what I’ve been doing:

Work
I’ve been steadily plugging away at Master Packing’s web site over the last two months. I’ve been trying to implement interactive features to some fairly boring things. Once its up, I’ll highlight what I’ve done, but until then, I’ve got to explain. On the mechanical packing page, I’ve used the Tree widget from Dojo to let you figure out which style of our mechanical packing matches other companies’ packing. Also, you can compare the temperature, pH, and speed ratings on all the mechanical packing we offer using the SortableTable widget. On the rail and marine page, you’ll be able to search for a partial or complete EMD number and the server will show you what part number we sell that part under and also suitable replacements. This search feature is something that isn’t available anywhere else in the EMD aftermarket industry. We should have it up and running by mid April. I’ll definately post when it’s up.

JavaScript
For the last month, I’ve been delving deep into the world of JavaScript for SitePen. It has taken me a while, but I think I’ve gotten the hang of the prototype-base inheritance that JavaScript uses. I think I’m past the fact that you can extend the prototype of any class so if you want a new method or want to modify an old method, you don’t create a new class. You just “mask” the old method on the current class. Coming from C++, that blew my mind.

Coaster
Development has pretty much stalled. I’ve been so busy with life, music, Dojo, Django, work, contracting, and everything else that I haven’t had time to sit down and code on Coaster for a long time. Also, the success of programs like Serpentine have shown me that other people are more motivated than I am. If someone wants to take the coding portion of the project over, contact me or Sean Harshbarger on the Coaster mailing list.

Updates

Man, I’ve been busy lately and haven’t had any time to work on Coaster. I haven’t even really had much time for anything other than work. Although I’ve had fun doing it, it’s been hectic.

Most of my time lately has been spent working on converting Master Packing’s current website over to Django so we can quickly develop new applications and easily edit content. I’ve been very impressed with Django’s infrastructure and API, and I’m even more impressed with how the next version is shaping up to look like. They’ve changed it so that a lot of the “magic” is gone and the API is improving. 1.0 should be sweet.

I’ve also been working with the Dojo javascript toolkit as well. It’s a pretty neat toolkit that is pretty powerful. I like how dojo.io.bind works for AJAX requests. They also have dojo.event.connect that works kind of like glib’s event connecting. The documentation is on the bare side (as in, not much at all), but that’s being worked on.