views:

200

answers:

4

I'm working on a project where we are doing a lot of custom javascript and especially jquery, on an mvc style project.

The only problem is that I keep adding more and more global functions/variables and they are piling up. I've got a few files but I'm unsure how to split some of the stuff up into separate files.

I've thought about composing some of these function and global variables into objects, but the object syntax in javascript seems a little awkward to me (because of the absence of classic classes). Though if I had a good example to follow maybe I could come around.

How do you deal with a project where the global javascript functions and variables start piling up like this?

+9  A: 

A very simple way to pile a bunch of global variables and functions into a single global object:

// Awful pile of globally-scoped names
var foo = 1
var bar = 2
function go = function(){
    console.log('Yeehaw!');
}


// Instead, just dump everything into a global-level object
var MyApp = {
    foo: 1,
    bar: 2,
    go: function(){
        console.log('Yeehaw!');
    }
}  

// Now access stuff like this
console.log(MyApp.foo);
console.log(MyApp.bar);
MyApp.go();

For "simple" top-level variables and functions, I can recommend this. There are plenty of improvements that can be made to this, but they'll probably fall under the category of premature optimizations; this is a great first step.

Triptych
Very clean solution. I'll use that approach in my javascript. +1
ichiban
This is what I do as well.
Chris Brandsma
Yes. And the MyApp methods will have access to everything else in MyApp through "this". Anything outside MyApp will use the MyApp prefix instead of this. Applies to anything triggered by an event or timer as well.
Nosredna
+1  A: 

You could break them up similarly to what jquery.ui does... by categories or by action/control

ex:

effects.blind.js
effects.bounce.js
ui.accordion.js

Can they be broken up into the Controls that they deal with?

Or by what they do?

Just some suggestions...

J.13.L
Thanks for the suggestions.
Mark Rogers
+2  A: 

The Crockford Videos on YUI theater are a good example of how to set up JavaScript namespaces among other things.

Tom Hubbard
Some good videos, thanks!
Mark Rogers
+1  A: 

If you are working with jQuery, the first way to organize your code is to build jquery plugins:

http://docs.jquery.com/Plugins/Authoring

http://www.learningjquery.com/2007/10/a-plugin-development-pattern

As you mentioned mvc, there is various javascript implementations out there, but I'm not sure they are hugely popular: jamal, javascript mvc,

http://jamal-mvc.com

http://javascriptmvc.com

Olivvv