In many frameworks, display code is separated from business logic. An MVC pattern is one of the many ways to accomplish this. When writing javascript featuring heavy UX changes such as in a sidebar it is very helpful to split up the data/state code from the pure animation code.
To accomplish this we use the CSS class as the interface between the two. This has the added benefit of letting two different developers work on those aspects separately with a minimum of integration issues in the end. Additionally this gives us the ability to reuse our ajax calls in different contexts.
In the following example we have a simple ajax enabled sidebar that loads data when a section is opened. The “interface” is the structure of the sidebar defined beforehand in xhtml.
<div class="sidebar">
<div class="sidebaritemheader">
</div>
<div class="sidebaritem">
</div>
<div class="sidebaritemheader">
</div>
<div class="sidebaritem">
</div>
</div>
This simple layout defines the interface that the animation and data aspects of the javascript will use. Each part needs simply attach their events to the appropriate element and javascript will fire them when needed. This example uses JQuery but you can use your javascript framework of choice, or even do everything from scratch should you me a masochist.
/**
* Animation javascript funtion
*/
function animate(){
//animation code here
}
// populates the sidebar data into the given container which is a jquery object
function populateSidebarData(xmlResult,sender){
//generate sidebar data items xhtml
//fill this out yourself
//calculate the insert container from the sender object
var sidebarItems = $(".sidebar").find("sidebaritem");
var index = $(".sidebar").find(".sidebaritemheader").index(sender);
var container = sidebarItems.eq(index);
//insert it into the container
container.innerHTML = sidebarInsert;
}
//getData method
function getData(populateMethod,sender){
.ajax(.....
//in the success section
,success
populateMethod(xmlResult,sender);
}
}
//main onload method
$(document).ready(function(){
$("sidebaritemheader").click(animate);
$("sidebaritemheader").click(function(){
getData(populateSidebarData,$(this));
});
});
as you can see the animation code and the data code are nicely separated and could even be tackled by 2 different developers if the complexity demands it. With this decoupling achieved you can be sure that any changes to the data code are not going to have repercussions in the animation code which I’m sure you’ll agree is a very good thing.
If you want to decouple this even farther, you can tell your designer to use a completely separate set of css classes for the visual markup and to not touch the data related ones. This ensures that your designer cannot inadvertently break the other ajax on the page.