tips for working on a large javascript project - javascript

I have some experience with JavaScript - but mainly with some small stuff, I never did anything really big in Javascript previously.
Right now, however, I'm doing quite a large javascript-related project, a jquery-powered frontend that communicates with the server-side backend by sending/receiving JSON via Ajax.
I'm wondering if you could provide some useful information on how to deal with large javascript projects - are there any helpful tools/libaries/good practices?
Thanks in advance.

My one big tip would modularize
In JavaScript, it is very easy for variables to clobber other variables. In order to avoid this, modularization is a must. There are several ways to take advantage of JavaScripts scope rules to minimize the possibility of variable conflicts.
var myProject = {};
myProject.form = function(p_name, p_method, p_action)
{
var name = p_name,
method = p_method,
action = p_action;
var addInput = function(p_input)
{
// etc...
}
return {
addInput: addInput,
name: name
};
}
myProject.input = function(p_name, p_type, p_value)
{
var name, method, value;
var setValue = function(p_value)
{
value = p_value;
return true;
}
return {
setValue: setValue,
name: name
};
}
// etc...
If you're careful about using var, and keep track of your function scope, then you have only one global variable - myProject.
In order to get a new form Object, you'd simply do the following: var myForm = myProject.form('form1', 'post', 'post.php').

You may want to check out Backbone.js
Backbone supplies structure to
JavaScript-heavy applications by
providing models with key-value
binding and custom events, collections
with a rich API of enumerable
functions, views with declarative
event handling, and connects it all to
your existing application over a
RESTful JSON interface.

Grigory ,
Even i moved from a backend to UI few months back only follow this approach
read all the concepts of jquery
either from google or through some
book or through jquery
documentation.
follow some of the jquery best practices http://psdcollector.blogspot.com/2010/03/77-best-jquery-tips-i-have-ever-read.html
write utitlity functions for all repeated code like getcookie ,subsstrings etc etc
keep getting your code reviewed by experienced person who can guide you
post to stackoverflow if you get stuck anywhere.
as it is big project divide into mutiple files and use proper naming convintion.
please let me know if you need anything else

jQuery and YUI 3: A Tale of Two JavaScript Libraries is a nice comparison of them in the context of a complex application, and gives useful hints for jQuery programmers as well.

The best advice is to keep your code segmented in different files as "classes". I personally hate working in a file that's more than a few hundred lines long.
Then assemble and minify your code with one of the tools on the web, like Shrinksafe or Google Closure Compiler
Note that Dojo, YUI, and Ext are all designed to handle large Ajax applications. You'll struggle a bit with jQuery. But I'm guessing this app isn't all that big and you should be fine.

Have you consider checking out MooTools?
MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API.

Related

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!

What JS library can be selected for RIA REST based application

I have ad idea to make some REST application. I already selected what I will use on server side.
But now I have a big big deal, what i should use to make RICH web app ?
I have middle javascript knowledges. I know jquery, I did my own jquery plugin. it should tell you about my level, so far from pro level.
But i would like to try make it by my self. And i'm thinking that jQuery it's not good choice for this kind of task. I would like to have something more flexible, and not looks like a lot of callback for specific events. Something maybe in MVC style.. But i don't want to spend a lot of hour to lear complicated stuff.
For example: ini PHP life there are a lot of frameworks, I choose Yii, it's really more easier to understand and make something, than Symfony (even 2nd version) for instance.
So i'm looking something similar Yii (but for a browser side), something fast, easy to learn, flexible and powerfull.
I thought maybe it could be cofeescript, or cappuccino or something else ...
BUT I don't have so much time to learn and try so many JS frameworks and libraries to make decision by my self, this is why i'm asking you all.
Thanks.
Typically my choice would be:
jQuery - for general stuff
Q promises library for handling of more
complicated asynchronous operations
Backbone for building model on the
client side
Mustache templates for interaction with HTML
Jasmine - for unit testing of the application
However if you plan to make very rich user interface, you need to handle many various events and you don't want to write your own visual controls (since they are complicated) you can go with ExtJS (note the potencial need to buy licence).
For me Jquery ui has always been easy to use with my limited javascript knowledge .The learning curve wasn't steep at all and lots of community plugins helped in the further development as well .
Apart from that you can try Mootools , Extjs (very nice components but requires a bit learning ) and yui (definite learning required for me ) .
I would recommend using jQuery because you already have some knowledge about it. When it comes jQuery UI it offers some functionality: http://jqueryui.com/demos/. Is this functionality RICH enough?
On top of jQuery, you can use several JS libraries to fullfil specific needs:
Charts:
http://www.highcharts.com/
Grid:
http://www.activewidgets.com/
When you are using JS it's really important that you keep your own JS code in good order. Devide your functionality into separate js-files. Think about your object structure. JS is prototypal language (you can inherit directly from other objects).
For me it took some time to find out the way to write good JS code. I highly recommend this book: JavaScript: The Good Parts (by Douglas Crockford).
// Namespace
var MyNameSpace = {};
MyNameSpace.vehicle = function() {
var that = {};
var my = my || {};
my.thisIsMyOwn;
that.publicFunction = function() {
my.thisIsMyOwn = "put something here";
};
return that;
};
MyNameSpace.car = function() {
var that = MyNameSpace.vehicle(); // "inheritance"
return that;
};

JavaScript messy code in large projects with jquery etc?

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
}
}());

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