I set myself a task: write some raw JavaScript for a web page. By raw, I mean no jQuery, no Prototype, no MooTools, just me and the editor.
Because I wanted to reduce the effect I had on the global footprint, I declared one global object like so.
var FOO = { // stuff initialize: function() { // setup stuff } };
So far so good. I then wanted that initialize()
function to run once the page was loaded. The immediate solution was this:
window.onload = FOO.initialize;
But that causes a problem in that, when the browser runs initialize()
, the this
parameter will not point to FOO
, but (presumably) to something like window
. Meh. Another issue: what if window.onload
was already set to something? I'd be stomping on it. I should instead call the old function and then call mine.
Some messing around later, I came up with this:
var FOO = { // stuff initialize: function() { // setup stuff }, addLoadHandler: function(func) { var that = this; var oldEventHandler = window.onload; window.onload = function() { if (oldEventHandler) { oldEventHandler(); } func.call(that); }; } }; FOO.addLoadHandler(FOO.initialize);
What's happening here? First of all, I'm now calling a method called FOO.addLoadHandler
and passing the FOO.initialize
function to it. This first takes a copy of the this
parameter (which is FOO
) in a variable called that
. It then takes a copy of the current value of window.onload
, and then sets it to a new anonymous function. The really cool thing about this function is the closure: it has access to the func
parameter, and the that
and oldEventHandler
variables when it is called. It checks to see if oldEventHandler
has a value and if so calls it. After that it calls the passed in func
.
Since we don't know what this
is pointing to on the call to the anonymous function (or, rather, we're not that interested), we need to call the func
parameter with the saved that
object, so that inside func
this
is pointing to the right object. This is done through the call
method.
And that's it. The code ensures that I'm chaining the existing handler (if any) for the window.onload
event, and that my initialize()
method is called with this
set to the correct object.
Now playing:
Dreadzone - House of Dread
(from ...360 degrees)
No Responses
Feel free to add a comment...
Leave a response
Note: some MarkDown is allowed, but HTML is not. Expand to show what's available.
_emphasis_
**strong**
[text](url)
`IEnumerable`
* an item
1. an item
> Now is the time...
Preview of response