What a good way to reorganize a growing number of javascript / jquery functions?

I am working on a project in which we do a lot of custom javascript and especially jquery in the mvc style project.

The only problem is that I keep adding more and more global functions / variables and they accumulate. I have several files, but I'm not sure how to split part of the material into separate files.

I thought about putting some of these functions and global variables into objects, but the syntax of the object in javascript seems a bit inconvenient to me (due to the lack of classic classes). Although, if I had a good example, perhaps I could come.

How do you feel about a project where global javascript functions and variables start to accumulate like this?

+6
javascript jquery object global-variables refactoring
source share
4 answers

A very simple way to collect a bunch of global variables and functions into one 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" variables and top-level functions, I can recommend this. There are many improvements that can be made with this, but they probably fall under the category of premature optimizations; This is a great first step.

+11
source share

Crockford videos at the YUI Theater are a good example of how, among other things, how to create JavaScript namespaces.

+2
source share

You can break them down similar to what jquery.ui does ... by category or action / control

Example:

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

Can they be broken down into the controls they deal with?

Or what are they doing?

Just some suggestions ...

+1
source share

If you work 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 are various javascript implementations, but I'm not sure if they are extremely popular: jamal, javascript mvc,

http://jamal-mvc.com

http://javascriptmvc.com

+1
source share

All Articles