Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to organize JS code in webapps where the main "meat" is still server side?

When building webapps with MVC web framworks like Django, Kohana, Rails and the like, I put together the application without JS-driven components initially, and then add them afterwards as "improvements" to the UI.

This approach leads to non-intrusive JS, but I don't have a good "standard" way of how to go about organizing the JS work. Most of the JS I write in apps like these are 10-30 line JQuery snippets that hook into some very specific part of the UI.

So far I often end up inlining these things together with the part of the UI they manage. This makes me feel dirty, I'd like to keep the JS code as organized as the python / php / ruby code, I'd like for it to be testable and I'd like for it to be reusable.

What is the best way to go about organizing JS code in a setup like this, where we're not building a full-blown JS client app, and the main meat is still server side?

like image 304
jakewins Avatar asked Nov 02 '10 18:11

jakewins


1 Answers

I am also very interested in what other people have to say about this. The approach I've taken is to use object literal notation to store the bulk of the function, and store these in one file included on all pages (the library)

uiHelper = {
    inputDefault:function(defaulttext){
    // function to swap default text into input elements
    },
    loadSubSection:function(url){
    // loads new page using ajax instead of refreshing page
    },
    makeSortable:function(){
    // apply jQuery UI sortable properties to list and remove non javascript controls
    }
}

Then I include a .js file on any page that needs to use the library that ties the elements on that page to the function in the library. I've tried to make each function as reuseable as possible and sometimes the event binding function on the page calls several of my library functions.

$(document).ready(function(){
    $('#mybutton').live('click',uiHelper.loadSubSection);

    //more complicated helper
    $('#myotherbutton').live('click',function(){
        uiHelper.doThisThing;
        uiHelper.andThisThing;
    });
});

edit: using jsDoc http://jsdoc.sourceforge.net/ notation for commenting for these functions can produce documentation for the 'library' and helps keep your code easy to read (functions split by comments).

The following question is along similar lines to your own - you should check it out...

Commonly accepted best practices around code organization in JavaScript

like image 144
calumbrodie Avatar answered Oct 13 '22 18:10

calumbrodie