Quick Javascript Tip: Pass an Options Hash

A quick Javascript tip that I pass along in a lot of code reviews is to make use of an options object as a hash to pass a large number of parameters to a function without writing each one individually.  For example:

function doSomething(id, someParameter, anArgument, optionC){ };

vs.

function doSomething(id, options){ };

By encapsulating the 3 additional parameters into an options object and passing them individually, you make for cleaner code.

A quick caveat is to check the options object to ensure that all of the necessary properties exist before running your function.  

More on Keeping Track of Focus

A bit over a year ago, I wrote a post on Keeping Track of Focus using Javascript.  Unfortunately, the code is severely flawed (though I haven’t yet figured out why it continues to work where I implemented it–but that’s a question for another day).

PPK points out that unlike most javascript events, focus does not bubble. He also offers a solution which uses event capturing to get around the problem.  I’ve taken that solution and modified it for use with Prototype.js as the original version was created that way.

var FocusReader = Class.create({

    initialize: function(){
	this.currentFocus = null;
        var focusRead = this.focusRead.bindAsEventListener(this);
        document.addEventListener("focus", focusRead, true);
        /* Also add the listener for IE which does not
            support capturing */
        document.onfocusin = focusRead;
    },

    focusRead: function(e){
        /* Need to force extending the event since
            it won't be extended by default */
        e = Event.extend(e);
        this.currentFocus = e.element();
    },

    getCurrentFocus: function(){
        return this.currentFocus;
    },

    getCurrentFocusId: function(){
	if(this.currentFocus.identify) return this.currentFocus.identify();
    }

});