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 usevar 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
Use Custom prefixed classes for UI hooks
ui-specificGuyProvided HTML
Bad – using style purposed classes/hooks
Adjusting the HTML
Good – using your own purposed classes/hooks
Only be as specific as neccessary
If this will accomplish your goal.
Then why have a selector that looks like this?
This simply introduces unnecessary DOM structure dependencies into the functionality you are building, and you should be able to be proactive in this regard because you should be providing your own hooks (prefixed classes) at this point right?
Ultimately though I would say that tight coupling between the DOM and the script are sometimes unavoidable because of the nature of how they work together.
Full Article