In the previous part of this entry, I went over the concept of context in jQuery and DOM manipulation, and why I think we should care about it. In this second part, I’d like to describe one way in I like to make use of context in real-world situations.

I’m an advocate of encapsulating Javascript functionality in an object-oriented manner using native Object Literals, following a rule of one object per application feature; one for navigation, another to enhance forms or provide an image gallery and so on. Aside from the benefits of encapsulation, it’s just a lot less problematic to scale and manage your javascript codebase across files and developers by organising code in this fashion.

Design patterns for writing javascript objects are in fair abundance in the wider Web. Some are much more strict about exhibiting true object-oriented features than others. One such is the ‘module pattern’ by Douglas Crockford. Personally, I tend to be a bit more lax about it, and simply use literals to reduce the number of objects and variables in the global namespace, while maintaining a quasi-OO structure. If you’re a PHP developer, you can think of it like the difference between OOP in PHP4 and OOP in PHP5. If you’re not, don’t worry.

A simple javascript object

0001var myObject = {
0002myProperty : 42,
0003myOtherProperty : 'Hello World',
0005myFunction : function() {
0006return this.myProperty;
0009myOtherFunction : function() {
0010return this.myOtherProperty;

get this code

With this code, we’ve contained our methods and properties in a single namespace, avoiding potential collisions with other Javascript code running concurrently.

Making the object useful

If one object is used for each feature we write, then each object should only ever have one context. It is a single static property which we will continually access. In the following example, a new object is created in which our desired context is an element with the incredibly imaginative ID of “element”:

0001var myFeature = {
0003 * Store our reference to the DOM element we're working on (the 'context')
0004 */
0005_context : false,
0007 /*
0008 * A simple getter function for this object's context
0009 */
0010getContext : function() {
0011if (this._context === false) {
0012this._context = $('#element');
0014return this._context;
0017highlightItems : function() {
0018$('.item', this.getContext()).css('background-color', 'red');
0022$(document).ready(function() {

get this code

It has a single property, _context. This contains the DOM reference returned from a regular jQuery selector call – $(’#element’). We can use this property throughout our feature’s code, passing it in as selector context or working with it directly.

However, since we will be using the object context a great deal, it makes sense to try and look for any quick-wins. By using a simple getter function, getContext() [line 10], we ensure the actual $(’#element’) function call happens only once, and every subsequent request for context simply returns the reference we’ve already stored in _context. This is a nice and simple optimisation; context shouldn’t ever change, we don’t have to rememeber to initialise the property at the start, and potentially save many unecessary getElementById() calls in our code!

In practice, we use the getter with a call to this.getContext(), as shown in the dummy highlightItems() function [line 18]. The first time it’s called, we retrieve the DOM reference. Do bear in mind that this only references the current scope. You’ll need to watch out for cases where you’re in a different scope, stopping you from accessing the property in this way – a subject for another day, perhaps!

Comments for "jQuery, it's all about context! (part 2)"

Commenting is now closed for this article

  1. Just found your site whilst looking for advice on optimising jquery selectors. You’ve written two concise and useful tutorials and, although alittle out of place on, I encourage you to do more of the same… and not to wait another 18 months to do so ;)

    On a side: love the concept of Beardscratcher, keep it up!

  2. Thanks! Yeah, I agree the content is a little unusual from everything else – at the moment. Indeed I want to focus on this sort of content from here on… just got to find the time to sit down and do it!




Previous Entries…

Journal content and design are © of Nick Skelton

built with web standards and a baseline.