Monday, 4 February 2013

Keeping the Javascript Beast Contained, Part 1: DOM Manipulation

Gradient, our product, has within it several -heavy components. Each of these is structured and functions quite similarly to a document-presenter desktop UI, with a visual hierarchy, top-level messages, routing components and distinct at the leaf-nodes of the hierarchy tree.

Having an organisation like this in Javascript leads to issues of containment, ensuring that each widget's manipulation is encapsulated to just the screen area belonging to that widget. While in the future, the introduction of the in will make this potentially easier, currently the encapsulation requires attention to detail and some HTML hooks.

The style we took in these widgets builds on top of , and makes use of HTML5 data-* attributes to hook into the DOM. Each widget has a container, defined by an HTML element with an id attribute. Within this container is a mixture of structural elements to define the look, and semantic elements marked up with a data-role. The data-role attribute delimits the particular aspect of functionality the element fulfills.

This can then be built into a widget by defining a top-level container selector, and then scoping all other DOM manipulation by this top-level selector.

The widget can now use the $title method internally and use the full jQuery API to manipulate it, safe in the knowledge that there won't be unintended conflicts with other widgets using similar roles in other parts of the screen.

The app object is the root of the widget hierarchy, and provides access to the DOM (through @app.$). More on this in a different post.

Examples are in coffeescript, as I feel this provides less obscuring of the basic idea, and avoids arguments over how I chose to do a javascript class, or how I maintained 'this' across scopes, rather than useful discussions about the central idea.

Edit 11th Feb 2012:
Altered post title to include 'Part 1: DOM Manipulation' as I'm turning this into a set of posts.
Added disclaimer about coffeescript examples.

No comments:

Post a Comment