JavaScript patterns. Closures, jQuery plugins

I’ve been re-writing a lot of JavaScript recently, as part of a move from Prototype to jQuery, and it’s given me a great chance to concentrate on how it’s written rather than what’s written.

Carousel implementation

Plugins are a major plus in jQuery, but they’re not suited to everything. A plugin is called to act on items in a collection, in the case of a carousel it would be the carousel container. A carousel is a perfect example of where a plugin is an appropriate solution, they’re also ripe to be created as objects, keeping all variables and functions contained and aligned to the element in question.

Tooltip implementation

Again these are suited to being plugins, but not as objects. When the plugin is initialised we can do a single pass to bind all the actions, we don’t need to store information about the state of the tool tip as we do with a carousel.

Lazy-loader implementation

My implementation of a lazy-loader is called as part of the init methods of a page, it’s classic functional programming and aims to be unintrusive when writing or executing code. I’ve implemented it using a closure (actually, using loose augmentation in the article below) where all methods but the initial call are private methods. Since it has no elements to modify it is unsuited to being a plugin.

Sources/Reading

Leave a Reply

Your email address will not be published. Required fields are marked *