JavaScript messy code in large projects with jquery etc? - javascript

Calling the javascript gurus out there.
Basically my question is regarding how you structure your code, both visually and for functionality for example do you wrap everything in objects using this structure:
var myapp={
binds:function(){
//put some event listeners for jquery etc...
},
otherfunc:function(){
//do some other thing
},
init:function(){
//call myapp.binds and other functions and other stuff to intialize your app.
}
};
Then finally
$(document).ready(myapp.init);
The thing is with a structure like this I think JSLint complains doesn't it? Whats the pros and cons using a structure like this or is there a generally better way to structure your code? Do you follow a certain pattern from $(document).ready(call) to putting all your event listeners and "initializing" your app, do you use separate objects for methods and variables?
I also think "visually" if you have a very large webapp this structure eventually looks very messy, but maybe it's just me I don't know, any input is appreciated thanks.

Using Inheritance Patterns to Organize Large jQuery Applications
explain in detail and with better practice by Alex
http://alexsexton.com/?p=51
its very very well explain, must see
other links
How To Manage Large jQuery Apps 5 months ago

It doesn't matter much how you structure your code as long as you follow the essentials rules of programming that your teacher thought you:
Don't write repetitive code
A function must do 1 and only 1 thing
Document your code
Some other small things but mostly the above... oh and apply lots of common sense

The only error you get from that is "implied global." You can get rid of the warning for document by using this.document instead (since window is the context). The implied global for $ will stay unless you paste in the jQuery source (then gl with all the errors in that).
I trust JSLint--a lot. On big projects I tend to make object literals as you did above but I use a module pattern for object security:
var myapp = (function () {
var secret_stuff, public_stuff;
return {
stuff: public_stuff
}
}());

Related

How to organize JS functions using objects

I would like to know if organizing JS functions in object notation is a good or bad practice. The intention is to keep js organized/easy to maintain.
Example:
var helper = {
myAlert: function(){
return alert('Alert from helper');
},
toLowerCase: function(){
var str = document.getElementById("txt").innerHTML;
return alert(str.toLowerCase());
}
}
Html:
<body>
<h1 onclick="helper.myAlert()">Hello Plunker!</h1>
<p id="txt" onclick="helper.toLowerCase()">Testing LowerCaseFunction</p>
</body>
Plunker
Thanks in advance!!!
code organization is an strategic topic when it comes to make software survive more than a couple of years yet this is also a very opinionated terrain.
You can make a nice job by keeping semantically related functions near each other under the same namespace, or even make it related to the user story being solved, it can be done in many ways.
If you want to know this approach is good enough, simulate an iteration on it, add a new feature and see what happens to the code.
The code avoids duplication? It gets reusable? Is it easy to locate and relate with the user needs? If so, then it will help you.
Finally, if applicable consider to use some module builder, webpack or browserify for example, so you will be able to not only separate your modules logically but "physically" too.
For me it is a good practice. When working with little projects, you do do see it important, but in large projects you are almost obliged to do it.
simply imagine you are making a chat website, you will need to create function that will delete messages, add messages. you can simply do it as you did it up.
var messages = {
remove:function{//remove code},
add:function{//add code}
}
in this way you can define contacts management object as
var contacts = {
remove:function{//remove code},
add:function{ //add code},
block:function{//block code}
}
This isn't really an answer per se but too long for a comment:
Since you are asking about best practices I'd like to point out a few things in your sample:
onclick. Just...don't. You don't want to grep through your JS trying to diagnose a behavioral problem only to realize 8 hrs in that its being called from HTML. That's a maintenance nightmare waiting to happen.
innerHTML again, just...don't. Unless you are working with HTML. 9 times out of 10, textContent will do and you can assign to it without security risk. Google 'innerHTML security risk' for more info.
alert alert blocks. Blocks your whole browser until you click annoying box. And which of your 50 open tabs was it in? Blocking is bad. Use console.log. You're a dev, and you do have devtools open right?
Your toLowerCase function. You mix data access (getting the DOM element's text) with data transformation. Bad idea.
Note that none of these are particular to JavaScript, they apply to pretty much all UI coding: don't mix business logic with the presentation layer, don't block user interactions, use the principle of least privilege, don't mix data access with data processing, etc. And all of the above issues are bigger problems than whether or not you namespace some functions.

How to make the javascript code easy to maintenance

All, I am working on a highly interactive web application which will need a lot of jquery or js code, And I'm finding that my code is becoming a little hard to maintain and is not all that readable. Sometimes even the author can't find the specified code.
So far what I had done for the clear code is below.
One js component in one js file .(for example. CustomTab.js is a tab component in my app.)
Using the templete to generate component HTML based on JSON.
Using Jquery UI.
Unobtrusive JavaScript.
Is there any other points I need pay attention? Anyway, Any suggestion or recommend technique for making js library/framework easy to miantanance is appeciated, thanks.
I could suggest you to use module pattern together with RequireJS to organize your JavaScript code. For the production you'll be able to use RequireJS optimizer to build your modules into one JavaScript file.
Also if you're expecting that your client-side application will be huge, consider to use some JavaScript MVC framework like Backbone.js together with the server-side RESTful service.
I use this namespacing pattern for my libraries:
MyLibrary.ListView.js:
var MyLibrary = MyLibrary || {};
MyLibrary.ListView = {
doSomethingOnListView: function() {
...
return this;
},
doSpecialThing: function() {
...
return this;
},
init: function() {
// Additional methods to run for all pages
this.doSomethingOnListView();
return this;
}
};
Whichever page needs this:
<script type="text/javascript" src="/js/MyLibrary.ListView.js"></script>
<script type="text/javascript">
$(function() {
MyLibrary.ListView
.init()
.doSpecialThing();
});
</script>
You can even chain methods if a certain page requires an additional function.
This is exactly the same question which I ask myself each time. I think there are few ways to get easy maintaining code.
Contribute in javascript opensource projects and understand how they solved that problem. I think you can gather some unique solution from each project and common part of projects structure will answer to your question about maintenance.
Use prepared solutions like backbone, knockout, ember or angularjs if I am not mistaken angular doesn't give you structure but provide you powerful tool for creating pages with less code. Also check todomvc for ready-made solutions.
Read books and try to create some structure for your needs. It will be difficult and long but result (maybe few years later :)) will be awesome.
Currently I'm also working on a JS framework for my company. What I'm doing is I use OOP elements for JS. In other words I'm implementing similar code to C# libraries(not that similar, simulating will be the correct word). As an example in C# you use Microsoft.Window.Forms, so I can use JSOOP and use method extending and overriding to create the same scenario. But if you gone to far in your project converting your JS code to JSOOP will be time consuming.
use JSLint, this will validate your code and bring down to a readable, script engine friendly code. Though JSLint is very strict so you can use JSHint also.
using seperate file for each component is a good idea I'm doing it also.
If you like you can download the jQuery developers version and you can have a general idea how they created the framework. I learned lot of thing looking at jQuery framework!

How do you organize your Javascript code?

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.
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?
For really JS-heavy applications, you should try to mimic Java.
Have as little JS in your HTML as possible (preferably - just the call to the bootstrap function)
Break the code into logical units, keep them all in separate files
Use a script to concatenate/minify the files into a single bundle which you will serve as part of your app
Use JS namespaces to avoid cluttering up the global namespace:
var myapp = {};
myapp.FirstClass = function() { ... };
myapp.FirstClass.prototype.method = function() { ... };
myapp.SecondClass = function() { ... };
Using all these techniques together will yield a very manageable project, even if you are not using any frameworks.
I use unobtrusive javascript, so, outside of the script tags I don't keep any javascript in the html.
The two are completely separated.
A javascript function will start when the DOM tree is completed, which will go through the html and add the javascript events, and whatever else needs to be changed.
In order to organize, I tend to have some javascript files that are named similar to the html pages that they use, and then for common functions I tend to group them by what they do, and pick a name that explains that.
So, for example, if I have UI functions then I may call them: myapp_ui_functions.js
I try to put the name of the application in the filename, unless there is some javascript that is common to several projects, such as strings.js.
I have (usually) one file that contains a bunch of functions and that's it. That is included in every page that uses Javascript. In the pages themselves, I'll make the calls to the functions like:
$(function() {
$("#delete").click(delete_user);
$("#new").click(new_user);
});
where delete_user() and new_user() are defined in the external file.
I too use unobtrusive Javascript, which for me means jQuery (there are other libraries that are unobtrusive).
You don't want a separate file for each page. That just means more unnecessary external HTTP requests. With one file—assuming you've cached it effectively—it'll be downloaded once and that's it (until it changes).
If I have a large amount of Javascript or the site is effectively split into multiple areas then I may split the Javascript but that's not often the case.
Also, in terms of my source code, I may have multiple JS files but I'll often end up combining them into one download for the client (to reduce HTTP requests).
More at Multiple javascript/css files: best practices? and Supercharging Javascript in PHP.
I've been rewriting a lot of my reusable code as jQuery plugins. I moved to jQuery from Prototype when I started doing ASP.NET MVC. Overtime I've migrated a lot my reusable code, or at least the ideas, from Prototype-based OO to jQuery-style plugins. Most of these are stored in their own JS files (mainly intranet apps so page load speed is pretty high anyway despite the extra requests). I suppose I could add a build step that coalesces these if I needed to.
I've also settled on a MasterPage approach that uses a ContentPlaceHolder for scripts that is right before the closing body tag. The standard jQuery/jQuery UI loads, and any other common JS goes right before the script placeholder in the MasterPage. I have tiny bit of JS at the top of the MasterPage that defines an array that holds any functions that partial views need to run on page load. These functions are run from the base document.ready() function in the MasterPage.
All of my JS is completely separate from my mark up. Some JS may exist in partial views -- these are encapsulated when the partial may be included more than once to make it specific to that instance of the view -- but generally not. Typically only included in the placeholders so that it's loaded at the bottom of the page.
Also, if you want to go OO heavy, check out mochikit: http://www.mochikit.com/
I find that developing your javascript using OO methodology is the way to go if you want it to be clean, readable and even somewhat secure. I posted the following question
Cleanest format for writing javascript objects
And got some fantastic responses on how to write my javascript code well. If you follow these basic principles you can use almost any library, such as yui, jquery and prototype, with ease.

What's a good way to refactor a growing number of javascript/jquery functions?

I'm working on a project where we are doing a lot of custom javascript and especially jquery, on an mvc style project.
The only problem is that I keep adding more and more global functions/variables and they are piling up. I've got a few files but I'm unsure how to split some of the stuff up into separate files.
I've thought about composing some of these function and global variables into objects, but the object syntax in javascript seems a little awkward to me (because of the absence of classic classes). Though if I had a good example to follow maybe I could come around.
How do you deal with a project where the global javascript functions and variables start piling up like this?
A very simple way to pile a bunch of global variables and functions into a single 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" top-level variables and functions, I can recommend this. There are plenty of improvements that can be made to this, but they'll probably fall under the category of premature optimizations; this is a great first step.
The Crockford Videos on YUI theater are a good example of how to set up JavaScript namespaces among other things.
You could break them up similarly to what jquery.ui does... by categories or by action/control
ex:
effects.blind.js
effects.bounce.js
ui.accordion.js
Can they be broken up into the Controls that they deal with?
Or by what they do?
Just some suggestions...
If you are working 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 is various javascript implementations out there, but I'm not sure they are hugely popular: jamal, javascript mvc,
http://jamal-mvc.com
http://javascriptmvc.com

Dynamic proxies in javascript?

I can proxy a single function in javascript by doing something like this (just jotted down from memory so bear with me)
function addAroundAdvice(target){
var targetFunction = target.aFunction;
target.aFunction = new function(){
invokePreCall();
targetFunction.apply(target, arguments);
invokePostCall();
}
}
Being a java programmer I'd think of this as a dynamic proxy. Every time I write code like this I think that someone must have made a really smart library that does the common proxying operations that is at least 10% better than what I can do in a hurry. I'd be expecting some stuff like correctly intercepting all methods for any given object, which may not be entirely trivial. Then there's different types of advice. So while I'm not expecting something the size of scriptaculous, it's certainly more than 6 lines of code.
So where are these libraries ?
Try jQuery AOP plugin
Looking at the source it seems that only uses jQuery as a namespace, so you could try this plugin even if don't want to use jQuery.
The Dojo Toolkit has a lot of support for AOP constructs like this:
Eugene Lazutkin's Blog Post on Aspect Oriented Programming with Dojo
The fact that you have been able to do it I would think means that there is a library to achieve it in the form of pure JavaScript i.e. your above example. Design Patterns can be applied to JavaScript as you know, so I think the advice I would provide to you is the following by a Google and Yahoo GUI developer :
http://jsdesignpatterns.com/
Chapter 14: The Proxy Pattern. Reference there solution to yours. You may still prefer your approach or you may find tips from their approach.
Cheers,
Andrew
I don't think you can intercept all functions.
The best you can do is iterate over all elements of an object and look for any functions:
for elem in someObject {
if typeof(elem) == "function" {
// replace the function
}
}
Trouble is, that if you add a function later it's not routed through the proxy.

Categories

Resources