Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle or minimize tight coupling in jquery

Description

By design most jquery code leads to a lot of tight coupling, e.g. selectors assume a specific structure of html

var mySubnav = $("#navigation a.sub-menu");

If the corresponding html changes, for whatever reasons,

<a class="subMenu" .... </a>

functionality is broken.

Question

  • What's the best way to handle tight coupling?
  • What approaches exist to loosen it up?

Answers, Approaches

  • use the html custom data attribute to separate css from js logic. e.g. add data-submenu="true" on the html and use var mySubnav = $("[data-submenu]"); on the js side.
  • implement a solid testing environment
  • couple as loose as possible, by using the least specific selectors, e.g. $("a.sub-menu'). See also
  • Eliminate the actual string literals that represent CSS selectors from the body of your jQuery code by (1) retrieving references to static DOM elements beforehand, and (2) storing selector strings in one place (at the top of your code).
  • use javascript frameworks, like Backbone, which decouple javascript from the DOM via views
  • use delegate and live regarding coupling due to event management
like image 893
SunnyRed Avatar asked Jul 25 '11 18:07

SunnyRed


1 Answers

This may not be a popular answer, but... testing, testing, testing. JQuery and Javascript in general are typically tightly coupled, and for good reason; they're code running in the browser, and so you want to keep the performance relatively snappy. So injecting an indirection layer that allows for looser coupling can decrease performance; as well, it can be a bit of overkill, since there's typically a close pairing between the JQuery / Javascript code that's written and the pages they're written for; this is as much an artifact of the historical development of Javascript, but that's the way that it is. As such, the tight coupling is pretty "normal".

The way to deal with this tight coupling, like any tight coupling, is to make sure that you've got good testing in place to cover any coupling failures. Testing can provide assurance that the coupling is proper, and it's really the best way to assure the functionality you expect anyway.

like image 122
Paul Sonier Avatar answered Sep 18 '22 23:09

Paul Sonier