The M in DOM stands for Model
A response to Ken Collins' post about encapsulation and jQuery.
I agree 100% with Ken that poorly organized code, code that litters on the global namespace, and code written such that it can't be reused is a sign of amateurness. However, I disagree that jQuery plays a role in leading developers astray regarding good software design principles.
jQuery is a library for working with the DOM and normalizing all the annoying variations across browser specific APIs. The way I like to think of it is: Your web application always has at least one model: the Document. Like any other object, it has state (e.g. the node tree, document properties) and behavior (e.g. adding and removing nodes). jQuery provides the interface through which you work with that object. jQuery is not a library for helping you model other parts of your application.
$.fn.flash = (content = null, htmlClass = "notice") -> flashElement = this.find("div.flash") .html(content) .removeClass("notice alert") .addClass(htmlClass) $.mobile.silentScroll(0) if content? flashElement.toggle(content?)
$.fn.flash plugin defined, we can use it to set the flash on any page:
$(currentPage).flash("OMG it worked!!! <3 <3 <3") # sets and shows flash notice $(currentPage).flash("Broken. (._.)", "alert") # sets and shows flash alert $(currentPage).flash() # clears and hides flash
I believe it has feature parity with Ken's example and is just as reusable, but has the advantage of being idiomatic jQuery that's simpler and has fewer dependencies.
The classical OO approach is not the only game in town for good software design. Don't forget that the DOM is already a model that has its own state and behavior, and jQuery plugins are your best bet for creating reusable code with naturally occurring encapsulation via scoped variables and closures.