1

I'm writing a new web application, I haven't got problem with backend part (it's my job until 6years) but i'm little new with frontend development (around 1 year). What's the best way to manage your JS code?

At this time I use a single file (app.js) where i call many function like this:

writer.init();
other.init();

writer and other are functions like this

function () {

var writer = {
  "init": function() {
    // do something
  }
}

}()

I think it's an ugly way. What are the best practices?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Jeremie Ges
  • 2,747
  • 3
  • 22
  • 37
  • Why exactly is that "ugly"? – JJJ Jun 15 '13 at 14:21
  • Object Oriented JS. Take a look at angular.js or backbone.js – Seth McClaine Jun 15 '13 at 14:21
  • 2
    Coffeescript takes care of the "ugliness". And any kind of build system can concatenate multiple source files into a single file (and minify it, too). – Thilo Jun 15 '13 at 14:22
  • knockout.js is your friend. Try googling it. – krishwader Jun 15 '13 at 14:22
  • @Juhana because you want to split functionality up for easier navigation and better performance. In the example given with just two objects its not a big deal, but if you have 500 objects with multiple functions it would take pages longer to render the js code and be harder to maintain. – Seth McClaine Jun 15 '13 at 14:24
  • Start by reading all answers on http://stackoverflow.com/questions/247209/current-commonly-accepted-best-practices-around-code-organization-in-javascript?rq=1 – Thilo Jun 15 '13 at 14:28
  • @all I use php to include at the good time (i think it's a best pratice but this way (use php) is worst. Sometimes i got just two lines of jquery to apply an effet, where i put this line ? In an other file ? I got an example of my practices in JS (http://www.benderphp.com) if you got a pretty solution, i'm ready to hear :) – Jeremie Ges Jun 15 '13 at 14:28

2 Answers2

1

I'd recommend using a JavaScript framework that enforces some structure, like using directives with AngularjS. If you want to do it all yourself, this chapter of Eloquent JavaScript is a good read.

mb21
  • 34,845
  • 8
  • 116
  • 142
0

The Asynchronous Module Definition (AMD) provides a very nice way of organizing code in modules. It is especially aimed for client-side Javascript code. There are various implementations but I would recommend having a look at RequireJS.

mor
  • 2,313
  • 18
  • 28