Kein
Kein

Reputation: 996

Splitting JavaScript code in several files: best practices

Im working only 2 weeks with ExtJS. And all my code looks like one big file. I have many included panels and other ExtJS objects in code. Looks like a big tree ) Can any give some simple advices for defining, storing code parts of JS files?

Upvotes: 5

Views: 1576

Answers (2)

wombleton
wombleton

Reputation: 8376

If you find yourself repeating code you can make those classes, and those can go into their own file. In addition you can split along panel lines regardless of whether they're repeated or not.

So for an application teaching users how to turn their minimally trained grizzly bears into lifetime companions, you might end up with files like this:

  • BearsAreNotDeadly.js
  • Search.js
  • Tutorials.js
  • GruesomePictures.js
  • ComplaintForm.js

... with each of those being a part of the application.

Upvotes: 1

Raynos
Raynos

Reputation: 169391

Things that fit into their own file fall into two broad categories:

Models

Any object constructor function. Any set of functions that handle data. Any business logic. Validation logic.

Anything that handles logically manipulating data on a page without writing / reading from the DOM.

Views

Anything that renders to the page. Template files. anything that manipulates DOM objects.

There are also miscellaneous things that fit into their own files

  • Server-Client communication, Websockets, ajax.
  • Micro frameworks
  • Utility belts
  • Routing helpers.

There are some things which are difficult to insolate into their owns files like the event based messaging that links your views to your models.

Generally you want to either use a packing tool to mix all your small files into one large file to send to the server or use a module loader like require.

Anything that you think can be modularized can be placed into its own file.

Upvotes: 3

Related Questions