How do you organize javascript files?
When I first started with Javascript, I usually just put whatever I needed into functions and called them when I needed them. That was then. Show Now, as I am building more and more complex web applications with Javascript; taking advantage of its more responsive user interaction, I am realizing that I need to make my code more readable - not only by me, but anyone who replaces me. Besides that, I would like the reduce the moments of 'what the heck, why did I do this' when I read my own code months later (yes, I am being honest here, I do have what the heck was I thinking moments myself, although I try to avoid such cases) A couple weeks ago, I got into Joose, and so far, it has been good, but I am wondering what the rest do to make their chunk their codes into meaningful segments and readable by the next programmer. Besides making it readable, what are your steps in making your HTML separated from your code logic? Say you need to create dynamic table rows with data. Do you include that in your Javascript code, appending the td element to the string or do you do anything else. I am looking for real world solutions and ideas, not some theoretical ideas posed by some expert. So, in case you didnt't understand the above, do you use OOP practices. If you don't what do you use? The single biggest challenge you'll have when building complex clientside applications is keeping your codebase from becoming a garbled pile of mess. If it's a long-running project that you plan on maintaining and changing over time, it's even harder. Features come and go. You'll experiment with something, only to find it's not the right call and leave traces of old code sprinkled throughout. I absolutely despise messy code. It's hard to read, hard to maintain, hard to collaborate on, and it's just plain ugly to look at. Beyond those pragmatic reasons, I consider my code to be my craft. Therefore, I want the care that I put into writing it to be obvious to those who read it. Complexity sneaks up on you. If you don't actively fight for simplicity in software, complexity will win. Here are a few techniques, crutches, coping mechanisms, and semi-pro tips for staying sane. Refactor early, refactor oftenEntropy is inevitable in a codebase. If we don't continually modify, simplify and unify the existing code along with the new code that's being written, we can easily end up with a really big, messy app. Some developers seem hesitant to touch code they've already written. But, I believe that deleting and updating code is a regular and important part of building an app. When you first start building an app, you don't know how you're going to build everything in it so there's no reason to treat any of the code you build along the way as infallible. Code is just text, not an edict. It can be changed easily and should be streamlined as you build. Don't be scared of refactoring. Be scared of building an unmaintainable piece of crap. I have found that to be much more costly in the long run. Additionally, if your app is separated into clean simple modules the risk of accidentally breaking something else is dramatically lower. Separating views and stateThis is the biggest lesson I've learned building lots of single page apps. Your view (the DOM) should just be reacting to the model state of your application. For this you could use any number of tools and frameworks. I often recommend reading the Backbone documentation to developers who are new to these concepts. It provides a clear "just JavaScript"™ approach to this and serves as a fantastic primer to the problems of building clientside apps. Essentially, you'll populate a set of models and collections of these models in memory in the browser. These will store all the application state for your app. These models should be completely oblivious to how they're used; they merely store state and broadcast their changes. Then you will have views that listen for changes in the models and update the DOM. This core principle of separating your views and your application state is vital when building large apps. One aspect of this approach that is commonly overlooked is the flexibility it provides if you decide the app should have a different UI ( CommonJS ModulesI'm not going to get into a debate about module styles and script loaders. But I can tell you this: I haven't seen any cleaner, simpler mechanism for splitting your code into nice isolated chunks than CommonJS modules. Let's pause for just a second to discuss what modules do for us. JavaScript has globals. What I mean is if you don't put a CommonJS is the same style/concept that is used in Node. By following this style you get the additional benefit of being able to reuse modules written for the client on the server and vice versa (though, the overlap is usually not that big). If you're unfamiliar with the CommonJS modules style, your files end up looking something like this:
That's it! Super easy. You don't create any globals. Each file that uses your module can name it whatever makes the most sense for use in that module. You just export a constructor (like above), or a single function, or even a set of functions. Generally, however, I'd encourage you to export only one thing from each module. Of course, browsers don't have support for these kinds of modules out of the box (there is no Browserify will create a Browserify is written for Node but even if you're using something else to build your web app, you can use Node and browserify to build your client package. Ultimately, you're just creating a single JS file. So once it's generated, that file can be served just like any other static file by any file server you want. Grab your moonbootsIf you're used to building apps where each script in your app directory has a corresponding As I touched on in Chapter 2, we really would like our production environment to serve a single, minified,
Since defining this type of browser app "package" is such a common problem that we want for all apps, I built a helper to make it a bit easier to work with. It's called "moonboots." To use it, you define your browser app like this (assuming Node and Express):
At this point we can tell Express the routes where we want it to serve our application. This is a bit hard to wrap your head around if you're not used to single page applications that do clientside routing. Since we're sending a JavaScript application, rather than rendered HTML to the browser, it's going to be up to the client to read the URL, grab the appropriate data, and render the appropriate page represented by that URL. So it's up to us to configure our server to always respond with the same HTML at any URL that is considered part of our client application. We cover the concept of clientside routing in a bit more detail in Chapter 9. You can do this in Express through the use of wildcard handlers, or by passing regular expressions instead of strings as the route definition. If you look at the sample application you'll see the relevant line in server.js looks like this:
Where The need for the wildcard URL becomes more obvious in your application when you open it and navigate to a different URL within an app that uses HTML5 push state. Say we click a button that takes us to A note on going to productionNode happens to be pretty good at serving static files. So just serving the production file with Node/moonboots is probably sufficient for most apps with moderate traffic. In production mode, moonboots will build and serve the app file from memory with aggressive cache headers. However, a lot of people like to serve static files with a separate process, using nginx or using a CDN, etc. In that scenario, you can use moonboots during development and then generate the minified file, write it to disk, or put it on something like an S3 as part of your deploy process. Calling The structure of the client folderOur client folder usually contains the following folders:
See Chapter 8 for a more in-depth discussion of templating. Creating an app globalSo what makes a module? Ideally, I'd suggest each module being in its own file and only exporting one piece of functionality. Only having a single export helps you keep clear what purpose the module has and keeps it focused on just that task. The goal is having lots of modules that do one thing really well so that your app combines modules into a coherent story. When I'm building an app, I intentionally have one main controller object of sorts. It's attached to the window as The main app object doesn't really need to be all that special. Often I create an object literal with a main init function (more on that in Chapter 10). But generally it will look like this:
Note that very last line that actually calls the Do I need to keep JavaScript files?Do I need to keep JavaScript files? No. Some JavaScripts are 100% necessary to correctly display your web pages. They are needed for certain website functions, for the use of advertisement or other important purposes.
What is the basic structure of JavaScript?JavaScript statements are commands to the browser JavaScript code is a sequence of statements JavaScript statements are separated with semicolon Multiple statement on one line is allowed JavaScript statements can be grouped together in code blocks You can break a code line after an operator or a comma.
|