views:

484

answers:

5

What are some strategies to achieve code separation in AJAX applications?

I am building a PHP application that I would like to have a nice AJAX front end on. I have long since learned to use some kind of templating in my PHP code to make sure I maintain good separation between my logic and display code, but I'm having trouble finding good ways to do this with the JavaScript code on the front end. I'm using jQuery to make the fetching of XML data and DOM manipulation easy, but I'm finding that the logic and layout code is starting to intermix.

The real problem is that I get XML data from the back end that then has to be reformatted and helpful text has to be wrapped around it (directions and the like). I've thought about sending over already formatted HTML, but that would require extensive reworking of the backend, and there must be a better way than what I have come up with on my own.

+2  A: 

I am not 100% sure I get what your issue but what you can do, especially if we are talking about a single page style AJAX application is to use Singletons classes geared toward specific tasks.

var XMLFormatter = function(){
    /* PRIVATE AREA */

    /* PUBLIC API */
    return {
        formatXML : function(xml){
            /* DO SOMETHING RETURN SOMETHING */
        }
    }
}();

What you are left with is a static XMLFormatter class that can be called anywhere on the page like so...

function useClass(){
    $('#test').update(XMLFormatter.formatXML(someXML))
}

This function can be used as a callback on the AJAX requests. I use this method for page logic by creating a Page class taht returns an object with an init method that is called when the page is loaded. The init method then attaches the various events and stuff to my page and it's elements. This is approach is talked about in Pro JavaScript Design Patterns well worth the read if you have the time and money.

It's also worth bearing in mind that Javascript is quite different in comparison to other languages and usually peoples best-practise approaches are usually just ones adapted from Java. While this is OK it's not using Javascript to it's full potential. Remember Javascript is quite event driven due to it's closeness to UI interaction and you will find a some event code mingling with other code. Crockfords website (http://javascript.crockford.com/) has some best-practice articles plus a number of other useful tips.

kouPhax
+4  A: 
  • write your templates in the HTML page, probably within a hidden element.
  • fetch data via AJAX calls, i find easier to use JSON, so you don't have to 'reformat' XML, it's only data.
  • apply the template to the data to generate HTML and insert into the displayed page.

check some jQuery templating plugins: jsRepeater, jTemplates, noTemplate, Template

Javier
I've been using jTemplates on my latest project to format JSON, it's definitely the most elegant solution I've seen so far.
tags2k
+2  A: 

I've been asking similar questions lately (here and here) and I've found a couple things that can help. I understand the same issues that you're finding with UI interaction being forced into code.

1: Write "classes" for the functionality and pass in the elements to modify in the constuctor, whether it's the ID for the element or the element itself, up to you.

2: Write "events" for the sections that may vary depending on the page or control. By events, I mean just placeholder methods that you can overwrite with actual functions. So for examples...

var FilterControl = function() {

    //the "event"
    var self = this;
    this.onLoadComplete = function() { };

    //This is the command that calls the event
    this.load = function() {
        //do some work
        ...

        //Call the event
        self.onLoadComplete();
    };
};

//somewhere else in the code
var filter = new FilterControl();
filter.onLoadComplete = function() {
    //unique calls just for this control
};

3: Get an IDE that is more Javascript friendly. I love my Visual Studio, but Apanta makes a outstanding IDE that has a really powerful Javascript IDE (it allows you to drag .JS files into a File References dialog so you get intellisense for all those Javascript documents solving one of the main reasons why it's hard to split up Javascript!

Hugoware
A: 

If I correctly understand the question, you're having a lot of HTML/javascript in same code block, and you want to separate them.

I would use several tricks to have a clean separation:

  • One JS file containing scripts/functions per actions group.
  • One JS file containing all common functions (XML parser, utilities...)
  • One JS file which (lazy-)loads specific script (item #1 here) and attach any events to currents elements on document loading.

The main problem would be to attach on-the-fly functions/events to generated code. IIRC, JQuery can handle this but not sure.

Hope it helps.

Pierre-Yves Gillier
A: 

I don't like formatting on the client so I always try to return HTML from AJAX callbacks unless I really need data for a choice list, for example.

The reason for that is I have a rich toolset on the server (ASP) for creating HTML and nothing on the client. I use a custom 'dynamic page' on the server which contains a 'dynamic control' that holds the template for the data I want to format. Only the contents of that control are emitted from the page.

The web service that AJAX calls merely does: return Execute(some-dynamic-page). Arguments to the web service are passed to the dynamic page either in the HttpContext bag or on the query string.

I find it easier to create a new dynamic page template on the server using drag and drop controls than using a client template or xml transformer. I haven't used any or the Jxxxx templating tools though - maybe they ease the pain.

Using that method, you can use the same separation (MVP/MVC, or simply code-behind) that you normally would.

Rob Kent