Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 905
Kein Avatar asked Oct 12 '22 03:10

Kein


2 Answers

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.

like image 192
Raynos Avatar answered Nov 03 '22 22:11

Raynos


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.

like image 43
wombleton Avatar answered Nov 04 '22 00:11

wombleton