Javascript Anti Patterns
Varun Grover
  
Lack of ­ Separation of concerns
//XYZ module
(function(){
//i first have to get some data from server
//then i have to create a dom using a template and applying this data
//finally i have to attach some event handlers to this
//of course the event handlers are also defined here in this module
})();
  
Too many responsibilities
//XYZ module
(function(){
//i have to listen to an event
//on event, i have to get some data from server
//on data, i have to process the response data payload. else on error, i
have to raise another event
//using processed data, i have to render some DOM.
//i shall also handle the DOM events for this DOM.
//on some interactions, e.g, a mouse move / drag-drop, i shall do further
stuff (eg. handle the dom changes, updating some data etc).
})();
  
I love Singletons / lot of privacy
//XYZ module
(function(){
//at parse time, i do some stuff
//then i create an object which has a really primitive public API
//finally i return this object
//(lets all pray that there are no unexpected side effects)
})();
  
Callback Hell
//XYZ module
(function(){
getDataFromServer(function(){
asynchronouslyRenderListOfItems(function(){
raiseOnRenderComplete();
});
});
})();
  
Lack of callback hooks
//XYZ module
(function(){
//i first have to get some data from server
//then i have to create a dom using a template and applying this data
//i have to attach some event handlers to this
//finally i append it to the dom
})();
  
Coupling event handler and logic
//XYZ module
(function(){
//i find the form and then bind to click of its submit button
$(form [type=submit]).click(function(){
validateForm();
submitFormViaAjax();
})
})();
  
Explicit Coupling is not good
function MyRotatorComponent(id) {
var contentElements = $(”.cta”);
contentElements.each(function(){
new CTA(this);
});
}
  
Implicit Coupling is WORSE!!
(function($){
function getSomeData(){
bindWithAnticipatedEvent
requestForData();
}
function bindWithAnticipatedEvent() {
//listen for an event that signals arrival of data
listen(a-verbose-event-name-string-that-makes-it-unique-in-the-system, doSomethingWithData);
//What the hell .. who is this stranger whom i need to depend upon for my core functionality
//how do i find it
//what if there are multiple strangers capable of sending this event
//am i then dependent on all / any one of them.. how is that determined
}
function requestForData() {
//raise an event and
}
function doSomethingWithData() {
//
}

JS Anti Patterns