Search code examples
javascriptjquerycode-structure

javascript / jquery code organisation


I would like to get some advice on structuring my javascript code and jquery functions. I like to use JQuery for dom event handling and ajax etc. I have written what seems like poor code in the past where my entire js file consists of a bunch of anonymous Jquery functions.

I am wondering - what does a "well structured" javascript file look like when combining with JQuery? Will there be many standard javascript functions and then some JQuery $() functions put in when needed? Is it ok to treat the code in a purely procedural way or would it be best to use some OOP concepts? I have always just had a bunch of functions which call each other hierarchically with helper functions here and there and no objects (aside from those used when using some random 3rd party library).

I am not a javascript programmer (mainly Java) so any advice from experienced js developers would be great.


Solution

  • Honestly, I try to apply MVC concepts to jQuery. Once you get over about 500 lines, not doing so just makes it hard to keep up with stuff.

    Model

    • Any locally cached data
    • Cookies
    • Reading-from/writing-to the server (AJAX)

    View

    • Basically all your DHTML stuff (HTML generation/manipulation, CSS changes, animations/effects, etc)

    Controller

    • Event handling (both user events and custom events)

    There are even some projects out there for this.