Internet Explorer Event Handler Leaks

If you’ve been developing for the open web for long, you’ll know that Internet Explorer is the bane of any web developer’s existence. The number of CSS bugs are enough to give any web developer a headache, but then add to that JScript’s deviations from the ECMAScript 3 spec and you have yourself a pain in the neck as well. Grab your favorite pain reliever, because there is another nuisance: memory leaks.

Leaks, Circular References, and Host Objects

There are two types of leaks in web development: single-page and cross-page. A single-page leak happens when an object is not collected by the garbage collector (GC) while the page is running, but is cleaned up when the page is unloaded. The cause of single-page leaks is usually an object being referenced unexpectedly. A cross-page leak happens when an object is not collected by the GC when the page is unloaded. We will be focusing on cross-page leaks in this blog post; from this point on, “leak” will refer to cross-page leaks.

The cause of cross-page leaks is usually circular references that trip up the GC. A circular reference is formed when object A references object B which, in turn, references object A. This seems to be pretty simple to avoid, but you can add more objects into the mix and still have a circular reference: A -> B -> C -> D -> A. In garbage collected languages, such as ECMAScript (which includes JavaScript and JScript), circular references are (or should be) handled and cleaned up properly. In fact, most implementations of ECMAScript do a good job of cleaning up circular references between native objects. However, ECMAScript 3 defined something called “host objects” that don’t have to follow the rules that natvie objects do (see What’s Wrong With Extending the DOM by Juriy Zaytsev for a run-down of host object wackiness). Circular references between host objects and native objects are what trips Internet Explorer up. In fact, all versions of Internet Explorer – except patched versions of 6 and version 7 – leak when you leave a page that contains code that forms circular references between host objects and native objects (yes, that includes version 8).

Why do I mention host objects and why can’t we avoid them all together? Internet Explorer implements DOM nodes and ActiveXObjects as host objects that wrap COM+ objects (the exception to the rule is version 8 where only ActiveXObjects are host objects; you can run this test to confirm the ActiveXObject leak). This wouldn’t be so bad, except the interaction between the garbage collection in JScript and the reference counting that COM+ objects use cause problems. When a native object (NO) is referenced, it is put on the “scavenger” list until it is no longer referenced; when a host object (HO) is referenced, the COM+ object’s reference count is increased and will only be destroyed when the reference count reaches 0. When a NO and HO are in a circular reference, the HO’s COM+ object’s reference count will be decreased when the NO is garbage collected or stops referencing the HO; the NO will be taken off the “scavenger” list when nothing references it – including COM+ objects. This means any DOM node or ActiveXObject that references native objects has the potential to leak when the page is unloaded. But all is not lost! The pattern is easy to identify and there is a fail-safe way to keep leaks from happening.

Identifying the Pattern

The basic pattern is this:

DOM_Node.objectRef ->
    Object ->
    Object.nodeRef ->
    DOM_Node

This translates to the following code:

var elem = document.getElementById("someElement"),
    obj = {};
elem.someObject = obj;
obj.someElement = elem;

This is pretty easy to spot (and is a reminder of why not to use expando properties that are non-primitive), but remember that you can add multiple objects into the mix and still have a circular reference:

var elem = document.getElementById("someElement"),
    obj1 = {}, obj2 = {};
elem.someObject = obj1;
obj1.someObject = obj2;
obj2.someElement = elem;

That seems easy enough, but there’s a much more elusive version of this pattern (adapted from the comp.lang.javascript FAQ on closures):

DOM_Node.onevent ->
    inner_function_object ->
    inner_function_object.scope_chain ->
    outer_activation_object ->
    outer_activation_object.nodeRef ->
    DOM_Node

This translates into the following (note the surrounding closure):

(function(){
    var elem = document.createElement("div");
    elem.attachEvent("onclick", function(){
        elem.innerHTML = "foo";
    });
})();

I’m not going to explain closures (for a good run-down, see the aforementioned FAQ), but the basic gist of what is happening here is a circular reference is formed through the activation object of the outer function when accessed through the scope chain of the event handler. In pseudo-code, the ES3 internals would look like this:

outer_activation_object.elem = document.createElement("div");
// The scope chain is formed by prepending inner_func's activation
// object to a copy of inner_func's [[Scope]], which is a copy of
// outer_func's scope chain.
inner_func.scope_chain = [
    inner_activation_object,
    outer_activation_object,
    global_object
];
elem.onclick = anonfunc;

As you can see, the reference chain looks like this:

elem.onclick ->
    inner_func ->
    inner_func.scope_chain ->
    outer_activation_object ->
    outer_activation_object.elem ->
    elem

Visiting one or two pages that leak won’t be too bad (unless they’re using an inordinate amount of event handlers). However, if you visit several pages that have circular references on them you will notice IE consuming more and more memory. I’ve put together a page that will leak in IE6 and refresh itself every 2 seconds to demonstrate the leak. You can use the system monitor to monitor overall system memory usage or a tool like Process Explorer to monitor the memory usage of individual processes. This example will be our starting point and we’ll look at a couple ways to keep a page like this from leaking. All of the examples in this article can also be downloaded in a tarball or a zip file.

If you look at the source of this leaky page, you will notice I include helper.js. As the name suggests, this file has some helper functions:

  • isHostType: A function to safely check for the presence of properties on a host object. If you’re not familiar with the reasoning behind this function or the gotchas of host objects, I suggest you read Peter Michaux’s article on feature detection. If you’re still looking at navigator.userAgent to know if you should use addEventListener, attachEvent, or elem.onevent = function(){} (DOM0), you need to read this article. The version of this function I’m using is copied from has.js.
  • _listen and _stopListening: Wrapper functions around the event registration mechanism supported by the current browser.
  • normalizeEventName: A function that makes sure the event name passed in is correct for the current browser.

As we look at the different ways to break the leak pattern, I will be modifying the listen and stopListening functions within source of the page; I won’t have to modify anything in helpers.js. Now that we have all of that out of the way, let’s start exploring ways to prevent event handler leaks.

Fixing It, the Microsoft Way

Microsoft is well aware of this problem; in fact, they have an MSDN article on leak patterns in IE, an article from Scott Isaacs, and a Knowledge Base article as well. Let’s take a look at the ways they recommend to fix the problem.

Detach on Unload

The first way that Microsoft recommends is to call elem.detachEvent(eventName, handler) in an unload handler. The example in the MSDN article mentioned earlier recommends storing the handler in an expando property of the node, however I won’t show that example here because storing things in an expando property of a node is a no-no in IE for a few reasons:

  • Changing an expando causes the node to re-render
  • Expandos with primitive values are cloned when you clone a node
  • Expandos that store non-primitive values can contribute to circular references

The third reason is the one that should make you wary of their solution; as we saw earlier, expandos are an easy way to make circular references and their solution is no exception. Suppose the node with the expando on it is destroyed via .innerHTML: unless we keep a reference to that node around, we’ve lost it and cannot detach the handler and we now have a leak.

A slightly better solution that runs in the same vein as Microsoft’s would be to register an unload handler, which forms a closure around the element, for each event registered:

function listen(obj, evt, handler){
    var e = normalizeEventName(evt);
    _listen(obj, e, handler);
    // unload every attached event
    window.attachEvent("onunload", function(){
        obj.detachEvent(e, handler);
    });
}

This breaks the circular reference manually by removing the reference to handler from the element. You can see for yourself in this example. Although this works, it could potentially be registering hundreds, if not thousands, of unload handlers (depending on its use). A better solution to this would be to use one unload handler with a cache of the arguments used to register each handler:

(function(global){
    var _evtData = {}, _emptyObject = {}, _nextId = 0,
        unloadAttached = false;
 
    function attachUnload(){
        if(isHostType(document, "attachEvent")){
            // one onunload handler to rule them all
            global.attachEvent("onunload", function(){
                for(var i in _evtData){
                    if(!(i in _emptyObject)){
                        stopListening(i);
                    }
                }
            });
        }
        unloadAttached = true;
    }
 
    function listen(obj, evt, handler){
        var id = _nextId++,
            e = normalizeEventName(evt);
        _listen(obj, e, handler);
        _evtData[id] = [obj, e, handler];
 
        if(!unloadAttached){
            attachUnload();
        }
        return id;
    }
    function stopListening(id){
        if(id in _evtData){
            var data = _evtData[id];
            _stopListening.apply(null, data);
            delete _evtData[id];
        }
    }
 
    global.listen = listen;
    global.stopListening = stopListening;
})(this);

The API changes slightly: listen now returns the ID of the cached arguments, and stopListening accepts that ID. It seems that this is a simple solution to a big problem!

This simple solution, however, introduces a new problem: adding an unload handler breaks the “back/forward” cache (or, bfcache) in modern browsers. Although we added a check for attachEvent in our attachUnload function to weed out Firefox, Safari, and Chrome, this would break bfcache in Opera (since Opera has attachEvent); it also could match IE10+ where bfcache might be implemented. Since there’s no reliable way to detect if a browser has bfcache, it’s best to avoid possibly breaking it.

Define Handlers in Another Scope

Another solution Microsoft suggests is to define all event handlers in a separate scope so the element isn’t in the handlers’ scope chain; the code shown in their example uses the global scope, but having all of your event handlers in the global scope is impractical for larger applications. For this solution, we’ll revert to listen and stopListening from the original leaking example and modify the loop:

while (++i < l){
    var hookupOnClick = (function(){
        function handler(){
            this.innerHTML = "foo";
        }
        return function(elem){
            listen(elem, "onclick", handler);
            return handler;
        }
    })();
    (function(){
        var e = document.createElement("div");
        var handler = hookupOnClick(e);
        // use stopListening(e, "onclick", handler) to de-register
        container.appendChild(e);
    })();
}

But do we really want to do that every time we set up a handler and for each event type? It also doesn’t look very elegant (IMHO). This solution is starting down the right path, though: we need to create the function attached to the node in a different scope. Care needs to be taken because it’s easy to just add another reference into the circular reference chain:

function createHandler(func){
    function handler(){
        func.apply(this, arguments);
    }
    return handler;
}
(function(){
    var elem = document.getElementById("someElement");
    listen(elem, "onclick", createHandler(function(){}));
})();

At first glance, this looks like it should work; a trained eye would see that this is just adding another reference into the chain:

elem.onevent ->
    handler ->
    handler.scope_chain ->
    createHandler_activation_object.func ->
    inner_func ->
    inner_func.scope_chain ->
    outer_activation_object ->
    outer_activation_object.elem ->
    elem

We need a way to break that chain.

Fixing It By Global Reference

As we’ve seen, accessing an element from a function through an activation object through the scope chain will cause a leak if it’s not properly cleaned up or worked around. However, there’s an interesting behavior I haven’t mentioned: a circular reference through the global object through the scope chain will not leak! This behavior was pointed out to me by John David Dalton. By combining this fact with what we’ve learned so far, we can create a generic event handling system that the browser will clean up after:

var _cache = {};
var createWrapper = (function(){
    var id = 0;
    function createLookupHandler(id){
        return function(){
            if(id in _cache && _cache[id]){
                _cache[id].apply(this, arguments);
            }
        };
    }
    function createWrapper(func){
        var cid = id++,
            wrapper = createLookupHandler(cid);
        _cache[cid] = func;
        return wrapper;
    }
 
    return createWrapper;
})();
 
function listen(node, evt, handler){
    var wrapper = createWrapper(handler);
 
    _listen(obj, normalizeEventName(evt), wrapper);
 
    return wrapper;
}
function stopListening(node, evt, handler){
    _stopListening(node, evt, handler);
}

Let’s analyze the reference chain created here:

elem.onclick ->
    createLookupHandler_inner ->
    createLookupHandler_inner.scope_chain ->
    global_object ->
    global_object._cache ->
    _cache ->
    _cache[id] ->
    LeakFunc ->
    LeakFunc.scope_chain ->
    outer_activation_object ->
    outer_activation_object.elem ->
    elem

As you can see, we have a circular reference but we’re going through the global object through a scope chain. _cache MUST be a global variable or reached through the global scope. Accessing _cache through an activation object through the scope chain will cause a leak. For instance, the following will leak:

var createWrapper = (function(){
    var _cache = {};
    var id = 0;
    function createLookupHandler(id){
        return function(){
            if(id in _cache && _cache[id]){
                _cache[id].apply(this, arguments);
            }
        };
    }
    ...
})();

Why? _cache is now accessible via the outer function’s activation object:

elem.onevent ->
    createLookupHandler_inner ->
    createLookupHandler_inner.scope_chain ->
    createWrapper_inner_activation_object ->
    createWrapper_inner_activation_object._cache ->
    _cache ->
    _cache[id] ->
    LeakFunc ->
    LeakFunc.scope_chain ->
    outer_activation_object ->
    outer_activation_object.elem ->
    elem

The following will also leak:

var _myCache = {};
var createWrapper = (function(_cache){
    var id = 0;
    function createLookupHandler(id){
        return function(){
            if(id in _cache && _cache[id]){
                _cache[id].apply(this, arguments);
            }
        };
    }
    ...
})(_myCache);

In this example, _myCache is added to the outer function’s activation object via the arguments (which are added to the activation object):

elem.onevent ->
    createLookupHandler_inner ->
    createLookupHandler_inner.scope_chain ->
    createWrapper_inner_activation_object ->
    createWrapper_inner_activation_object._cache ->
    _myCache ->
    _myCache[id] ->
    LeakFunc ->
    LeakFunc.scope_chain ->
    outer_activation_object ->
    outer_activation_object.elem ->
    elem

The object used to store the function references MUST BE REFERENCED THROUGH THE GLOBAL SCOPE. My best guess as to why is that somehow IE6 will increase the reference count of a COM+ object (in this case, a DOMNode) when it is referenced through an activation object through the scope chain. However, it seems that looking up an object through the global scope (which means you’re ultimately going through the scope chain) doesn’t have this same effect. If someone can shed some more light on this, I would be much obliged. I have set up a gist to try to explain what is going on in terms of the ES3 spec and I would appreciate any corrections there as well.

The following examples will not leak because they all ultimately look up functions through the global scope:

var createWrapper = (function(global){
    global._cache = {};
    var id = 0;
    function createLookupHandler(id){
        return function(){
            if(id in _cache && _cache[id]){
                // note that we're referencing _cache
                // via the global scope
                _cache[id].apply(this, arguments);
            }
        };
    }
    ...
})(this);
var my = {
    really: {
        long: {
            namespace: {
                _cache: {}
            }
        }
    }
};
var createWrapper = (function(){
    var id = 0;
    function createLookupHandler(id){
        return function(){
            // note that we're not closing around
            // any part of the namespace object
            var _cache = my.really.long.namespace._cache;
            if(id in _cache && _cache[id]){
                _cache[id].apply(this, arguments);
            }
        };
    }
    ...
})();

Event Handlers in Libraries

I’ve taken the liberty of writing some leak tests for the latest versions (at the time of this article) of 6 of the most popular JavaScript libraries used today (full disclosure: I am a Dojo committer). I have included the results of the tests on IE6 version 6.0.3790.3959 running on Windows 2003 (this version doesn’t have the patch applied to it to fix the circular reference leak). Note that I have not included which method the library uses to prevent leaks, just if it leaks or not:

Conclusion

From all that we’ve seen here, the following pattern (or one similar to it) should be used to prevent leaks in event handlers in Internet Explorer without having to use an unload handler:

var _cache = {};
 
var createHandler = (function(){
    var id = 0;
 
    function createLookupHandler(id){
        return function(){
            if(id in _cache && _cache[id]){
                _cache[id].apply(this, arguments);
            }
        };
    }
 
    function createHandler(func){
        var cid = id++,
            handler = createLookupHandler(cid);
 
        _cache[cid] = func;
 
        return handler;
    }
 
    return createHandler;
})();
 
elem.attachEvent("onclick", createHandler(function(){}));

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.

Back from hiatus

It’s been a long long time since I’ve seriously blogged and I’m going to get back into it again (at the behest of David Walsh). I’ve got a couple of tutorials and/or tips lined up and I intend to keep up with it. Alright, back to your regularly scheduled programming…

Recipe for Brye

A few people have asked me for this after I made mention of it in my status updates. This is a Forbes-family treat that is great when you’re feeling crummy. We used to have it all the time when I was a kid and we were home from school. I just learned the other night that it’s actually a dessert (I would never have guessed). Anyway, here is the recipe for Brye:

Ingredients:
2 cups milk
1/2 cup sugar
1/4 cup flour
pinch of salt
1 tsp vanilla
1 egg
2 tbsp butter

Directions:
Put the sugar and flour into a medium saucepan. Measure the milk in a glass measuring cup and pour into saucepan. In the same measuring cup, whisk the egg and pour into saucepan. Bring to a boil. Add the butter, vanilla, and salt and stir until it thickens. Let it cool a bit before partaking!

A petition to take back our freedoms

I know it’s been a long time since I’ve written a real blog post, but I wanted to make sure everyone knew about this: A petition to bring articles of impeachment against the Bush administration. If you have the time, please read the articles. For those of you who don’t like to read and would rather watch something (or even listen to it), please check out these links:

Hearing on Limits of Executive Power: Dennis Kucinich
Hearing on Limits of Executive Power: Bruce Fein
Hearing on Limits of Executive Power: Vincent Bugliosi
Hearing on Limits of Executive Power: Robert Wexler

I want to let everyone know that I’m not a war for oil, moveon.org, or Bush==Hitler person. I voted for Bush in 2000 and 2004. I supported the Bush administration’s decision to go into Afghanistan to fight Al-Qaeda. I even bought the need to go into Iraq. But I’m also a person who believes that if you make a mistake, you don’t cover it up: you own up. I believe that when an someone abuses the power they have been given, they need to be held accountable. I urge you to read the articles of impeachment and watch the clips and decide for yourself.

If you support our troops…

I know I’m way overdue for an update, but I had to post this. I’ve also tried to stay out of the political posting this season, but I thought I’d post this. The mainstream media has done an excellent job of squelching a fine candidate: Ron Paul. Yes, he has very libertarian stands and that’s what appeals to me: he believes that the federal government should only take care of what is outlined in the constitution. It seems like his message is resonating with our troops (warning: Flash content follows… I’m not a big fan of proprietary technology, but I feel like this needs to be spread):

Via Daily Paul.

Through field and barbed wire

So last night, Asaph’s Apprentice drove down to Lamoine Christian Service Camp last night to play a show. It wouldn’t have been too much of a hassle, except that we got our directions from MapQuest (no link love for them… you’ll soon see why).

Here are the directions we used. Note directions #14 and #16. Right turns on CR-2800… easy enough. Or so we thought. The first turn onto CR-2800 goes through some guy’s field and ends up where the directions say it should. The second turn onto CR-2800 is a little more misleading. If you click on the map link for direction #16, it shows you a nice straight road… this is not what CR-2800 currently looks like. We ended up driving through another field and ended at a barbed wire fence. I wish we would have taken a picture… it was priceless. Thank you MapQuest.

Of course, Google Maps doesn’t get it any better and Rand McNally fails miserably as well. The only directions site that gives directions that don’t end up in the middle of nowhere (literally) is Yahoo! Maps. And their directions end up taking less time too.

What is it with these map sites? Why don’t they have a review feature? It ended up taking us an hour more to get to the camp because we had to backtrack out of the field (while bottoming out a couple of times) and then flagging down someone who’s first question to us was, “Are you guys looking for the camp?” If we hadn’t have planned to get there 2 hours early, we would have been late. And yes, I know that all of these map sites have their little disclaimer that says something to the effect of “if these directions suck and you end up in the middle of a field or lake or get eaten by cannibals it’s not our fault,” but seriously… it’d be nice to be able to get alternate routes from people that actually live in the place that you’re going to or have been there before.