Best way to work with angularJS and jquery's $('document').ready() - javascript

I have a bunch of pages given to me by a designer that has to be integrated with my existing project in AngularJS.
The page that I have been given uses a lot of jquery . The one thing that is causing problems is the jquery's $('document').ready() function.
Since in an angular project the page is just loaded once, most of the document.ready() parts in any of the pages are not working. Every time a page changes, there is some code to inside this function that doesn't work.
So whichever controller in my project is supposed to have any code that work's on document.ready I am throwing it in the controller like this :
setTimeout(function(){
$scope.$apply(function() {
var _wht=($(window).height());
var _wwt=($(window).width());
_wht=($(window).height());
_wwt=($(window).width());
if(_wht > 450){
var mcht = _wht - ($('header').height()+ $('footer').height()+50);
$('.login-page').css('height',mcht+'px');
$('.login-page').css('padding-top',((mcht - 158)/2) +'px');
}
});
});
This works very well.
But I think this counters angularJS' philosophy of separation of concerns . The controller is where you have only your business logic.
Where is the best place to throw this piece of code ?

AngularJS is here to be built for robust arhitecture and that is why we see so many modules in terms of directives and other components. Putting JQuery with it will be like going away from their core design and you will yourself end up in a mess maintaining the codebase.
jQuery is a crutch if you are writing AngularJS applications.
If you’re starting an AngularJS app, take a good look at ng-boilerplate. Then take a look at ui-bootstrap’s directives. They are a living example of how you can do “jQuery things” with a fraction of the code, and build an app that is easier to maintain, way more testable, and generally nicer to work with.
Take a look at this stuff
How do I “think in AngularJS” if I have a jQuery background? - An excellent Stack Overflow post that expands on this viewpoint
Using AngularJS? Then stop using jQuery
Instead of $('document').ready() you can also use.
angular.element(document).ready(function() {
:
:
});

Related

Thinking in Angular Way

I am working on project with more than 1500 HTML pages.
This project was previously implemented in jQuery and JS code. Now I have to revamp this SPA using AngularJS.
I have gone through basics of angularjs. We have several interaction on in our projects (Moving from one page to another).
Is <head ngapp="routingApp"> is the right place to configure the routing for whole project or can I define it separately for each module?
As the project also uses jQuery for bootstrap dependency does it make any sense just to include jQuery for bootstrap?
I would strongly discourage you from declaring all your routing in one file. It will lead to really big file & bad maintainability.
If you have such a big project I'll advise you to read the Google's recommendation for AngularJS structure first.
Then every developer will have a way to 'scope' his work within one module & it would be easier for him to understand it.
Moreover it would be much easier to disable/enable some modules just by excluding them from final composing&"compilation" phase.
E.g. you'll have a module that defines routes that can be reached within this module.
I strongly recommend using Gulp & Bower (you'll have to have Node.js) to manage you dependency management as well as composition/compilation phase management.
As a teaser here you have gulp scripts compilation for fractal structure:
gulp.task('scripts', function () {
var depJS = dependencies.bower.js.map(function (dep) { return config.bowerLib + dep; });
depJS = depJS.concat(dependencies.node.js.map(function (dep) { return config.nodeLib + dep; }));
var srcJS = ['app/modules/app.js', 'app/modules/**/*.module.js', 'app/modules/**/*.js'];
var libPipe = gulp.src(depJS)
.pipe(plumber())
.pipe(concat('lib.min.js'))
.pipe(size({title: 'js-before lib'}))
.pipe(gulpif(config.minimize.perform, uglify(config.minimize.js)))
.pipe(size({title: ' js-after lib'}))
.pipe(gulp.dest(config.scriptsOutDir));
var pipe = gulp.src(srcJS)
.pipe(plumber())
.pipe(concat('all.min.js'))
.pipe(size({title: 'js-before all'}))
.pipe(gulpif(config.minimize.perform, uglify(config.minimize.js)))
.pipe(size({title: ' js-after all'}))
.pipe(gulp.dest(config.scriptsOutDir));
});
The second question - AngularJS have jQLite inside it. When the jQuery is available the jQuery implementation is used. (side note: use jQuery/jqlite only in directives). It depends how vastly the jQuery library is used throughout your project & what methods are used. Can it be replaced by jqlite (limited jQuery) or can you just rewrite all jquery specific DOM/etc. manipulation by directives.
You've mentioned bootstrap - did you mean Twitter Bootstrap? If so, look at the AngularJS UI-Bootstrap
You can definetaly separate it in modules, look at https://github.com/angular-ui/ui-router.
1.) If you are asking if its right to define whole routing inside 1 index.html and one angular app , yes it is right place. It is purpose of SPA

symfony2 + javascript framework

My quick question is, should I begin using a javascript framework at the same time that I build my project with symfony or can I do it later without major troubles?
I have a small project of one page app written in flat PHP and jquery. Now I'm trying to port my project to symfony and I would like to use a javascript framework too. After one month of learning symfony I think that I begin to understand how it works, but I have a mess in my head with all those javascript frameworks available.
I think that is better to focus all my attention to symfony and once I fully understand how it works try to use a framework for javascript.
But I'm afraid of using a javascript framework implies changing a lot of my symfony code and twig templates. Right now, I'm using repositories and services to get data for the controller and then return it to javascript in JSON format. I understand that this shouldn't change (at least the part where I get the data) but I read some articles of people using bundles like FOSRestBundle and JMSSerializerBundle to return the data and using templates from javascript like mustache to render it, so I'm a little confused and I don't know if this will be a big change or if this is needed between symfony and javacript framework.
EDIT:
When I say javascript framework I'm talking about a combination of backbone + chaplin or marionette, for example. I think that jquery is just a library, not a framework, and backbone needs jquery to work.
All websites are completed by JS now, to be more user friendly and interactive, so yes of course you can use JQuery right now, from the beginning of your project because if you don't you will lose time by refactoring your actions to works with JS interactions and callback !
In addition, it will learn you how to manage JS in a Symfony project. You are free to use a vendor bundle or not to return JSON. You can simply do like that :
// action :
public function myAjaxAction()
{
// do something
return new Response(
json_encode(
array(
'success' => 0,
'error' => 'No image found.
)
));
}
And to finish, some documentation of Symfony2 use JQuery, like this : http://symfony.com/doc/current/cookbook/form/form_collections.html
So yes you can use JQuery now !
I'm not getting you. If you want to convert flat JS into JS framework in the future, why don't you use that from now on? From my experience, it's not easy work to convert your js(jquery way) into REAL Backbone way. Because you need to reconstruct all of your js code, even symfony code.
Though it's harder to use two new kind of technologies for you, I think you should try it.
Yes, you can use it very easily. Symfony is mostly for backend. You can put in Backbonejs or Angularjs for front-end stuff.

Organizing javascript code

I am making a javascript application. Normally what I do is make different modules and get users inputs or click events in $(document).ready(); function. This works fine for small applications. But when I follow the same pattern, I mean getting click events in $(document).ready(); then it gets messy.
So how can I organize this file for a huge application?
Thanks in advance
The single-best resource I've found on this subject is Addy Osmani's creative commons book, Patterns for Large-Scale JavaScript Application Architecture. It is based in part of Nicholas Zakas' Scalable JavaScript Application Architecture, adapting it to classic design patterns and a modern workflow.
Once you reach even a modest-level of complexity, you'll benefit from working with a framework built using a variation of the MVC architecture pattern. Backbone.js is the frontrunner and is a micro-framework, meaning it does less hand-holding than others. Other popular choices are Ember.js, KnockoutJS.
Extensions and boilerplates are also built on these frameworks to handle repetitive tasks such as data/model binding and scaffolding. For Backbone, check out Backbone.Marionette from Derick Bailey and Backbone Aura, a not-quite-ready-for-production adaptation of the Osmani/Zakas architectural model built using Backbone as its... well, backbone.
Being JavaScript a scripting language, structure is one of the far most important concerns in large scale Javascript projects. It is important the parts of your application are well decoupled and 'self contained'. For an example, you may create your own UI components having its own template, logic, style, localizations, etc. in a single folder. Such self containment will let you organize your complex front end code in a manageable way.
Once you have your code organized, and self contained, there are other concerns that you need to address too.
How should these loosely coupled components interact with out tight coupling
How should I optimize these individual parts to load fast in my production env
I'm the author of BoilerplateJS reference architecture for large scale applications.
http://boilerplatejs.org
It incorporates most of the best practices discussed in Nicholas Zakas'presentation. You will find a sample implementation of a modular product suite in the code as well. Have a look, you will understand the concerns you will need to pay attention in doing a large scale application with JavaScript.
Let suppose we make cross platform application like below
Sorry for dirty content removing.
We want it cross platform so we write it with JavaScript. We want our syntax to be smart, elegant and laconic, so we use jQuery.
Our source structure will be like this
In js folder we have three folders: controller, model, view. We divide our application to three (can be many more) parts: main, menu and navbar.
For each of these parts we have ...Ctrl.jsand ...View.js. We have only one model mainModel.js (just in case).
Ctrl.js is where your handlers and where you attach them to controls. For example mainCtrl.js:
app.mainCtrl = {
model: app.mainModel,
init: function(){
$('#addButton').click(function(){
this.model.addToFavorites();
});
$('#removeButton').click(function(){
this.model.removeFromFavorites();
});
}
};
(small stars on the right of the above screenshot are actually add/remove buttons )
Controller can hold references to both view and model or only to model (as in above example).
Model.js is where we update our backend and view. For example mainModel.js:
app.mainModel = {
view: app.mainView,
all: {},
favorites: {},
init: function(){
/* for example
this.all = $.parseJSON ($.load('url'));
this.favorites = $.parseJSON ($.load('url'));
*/
this.showAll();
},
showAll: function(){
this.view.show(this.all);
},
showFavorites: function(){
this.view.show(this.favorites);
},
addToFavorites: function(item){
//add item to favorites
},
removeFromFavorites: function(item){
//remove item from favorites
}
};
View.js is where we actually updates our view (by directly manipulating DOM). Methods of view can be called by related controller and/or model. For example mainView.js:
app.mainView = {
show: function (items){
//create new element for each item
}
};
And finally we have app.js file where we initialize our app:
var app = {
init: function(){
this.mainCtrl.init();
this.menuCtrl.init();
this.navbarCtrl.init();
this.mainModel.init();
this.navbarView.init();
}
};
We have only one global variable app in our application. All views, controllers and models created inside app namespace.
And finally, finally is the order of import. You should import app.js first as it defines app variable.
<script src="vendor/js/jquery.min.js"/></script>
<script src="js/app.js"/></script>
<script src="js/controller/mainCtrl.js"></script>
<script src="js/controller/menuCtrl.js"></script>
<script src="js/controller/navbarCtrl.js"></script>
<script src="js/view/mainView.js"></script>
<script src="js/view/menuView.js"></script>
<script src="js/view/navbarView.js"></script>
<script src="js/model/mainModel.js"></script>
<script>
$(function(){
app.init();
});
</script>
</body>
</html>

UI Patterns in JavaScript

What UI patterns do you usually use in JavaScript?
By UI patterns I mean best practices to be used to build and organize UI, generated/managed from JavaScript (apart from libraries like jQuery or YUI).
For example, if you came from .NET world you are familiar with MVC (Model-View-Controller) patterns family. In the world of WinForms and ASP.NET you will meet Model-View-Presenter. In WPF most likely you will find MVVM (Model-View-ViewModel) approach.
And what about JavaScript?
Patterns are usually language-agnostic. If a pattern has value, barring certain edge cases it will have value regardless of what language or technology you're using. Take MVC. The concept of separating the model from the view from the controller has value regardless of whether the model is implemented with an RDBMS or some other technology, whether the view is HTML or Swing or X.
Where you see certain patterns applied more in one technology than another, it usually just means that the developers of the technology had a particular approach that they supported more fully than others.
JavaScript itself doesn't impose any particular pattern on you. Some JavaScript frameworks, like YUI or Dojo or Glow will tend to lead you one direction more than another.
At the end of the day, look at the problem you're solving, the resources and experience you have, and follow the patterns that make sense.
I'd like to recommend Ross Harmes & Dustin Diaz's book, Pro JavaScript Design Patterns, definitely the best resource on this subject, and definitely worth a read.
There’s also a very interesting article on JavaScript MVC in the latest issue of A List Apart.
A good approach to building GUI application is that of browser:
using markup for UI layout
using javascript UI logic
using CSS for UI styling
Most of modern GUI frameworks (ExtJS, Dojo etc) offer APIs that greatly help building GUI in JavaScript solely. But there is another GUI framework Ample SDK that brings the before mentioned separation of concerns. It allows for using XML-based languages (XHTML, XUL, SVG) for layout, CSS for style and DOM APIs for UI logic.
To orchestrate a client-side GUI application you can use either MVC or a little bit more advanced pattern PAC, as for the former - there is a PureMVC implementation available
Take a look at the following snippet (only concerns UI logic, not app logic, to be built with MVC/PAC):
index.html
<script type="application/ample+xml">
<xul:tabbox onselect="fOnSelect(event)"
xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<xul:tabs>
<xul:tab label="checkbox" />
<xul:tab label="textbox" />
<xul:tab label="datepicker" />
</xul:tabs>
<xul:tabpanels>
<xul:tabpanel>
<xul:checkbox />
</xul:tabpanel>
<xul:tabpanel>
<xul:textbox />
</xul:tabpanel>
<xul:tabpanel>
<xul:datepicker />
</xul:tabpanel>
</xul:tabpanels>
</xul:tabbox>
</script>
index.css
#namespace xul url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
xul|tab:focus {
color: red;
}
index.js
function fOnSelect(oEvent) {
alert(oEvent.currentTarget.selectedItems.length)
}
As i know there are no specific patterns for Javascript yet. But I think there is a potential for something like widgets(component) approach. Since mainly we use javascript to empower our html code. It is logically that we should connect our every javascript object to html tag. So here we have something like Model(jsObject)+View(HTMLrepresentation). To get MVC we need controllers and we have Events for this. In this case we will have incapsulated easily extensibel component.
for example:
// this is a part of some FormValid.js
<script>
function FormValid(){
}
FormValid.prototype.validate=function(){...}
</script>
//this is our HTML
<form id="form1"...onsubmit="this.jsObject.validate();">
</form>
<script>
//all the following stuff could be solved in one line, but you need to create some helper. Like Components.Attach("FormValid").to("form1");
var newObj=new FormValid()
var form=document.getElementById("form1");
from.jsObject=newObj;
newObj.htmlObj=form;
</script>
Also I have an idea of using template engines like Zparser to separate view and model. I am developing js library for this, so I am in this question right now.
We have core object with view method. All our classes have it like a prototype at he end. This method gets templates property of class and using some templates parser generates HTML basing on our model. This HTML is inserted in htmlObj node so the VIEW of our object is updated. This is basically an idea and our code becomes:
// this is a part of some FormValid.js
<script>
function FormValid(){
}
Components.extendCore(FormValid);
FormValid.prototype.validate=function(){...}
</script>
FormValid.prototype.templates={
main:'<form class="form1"...onsubmit="this.jsObject.validate();">...</form>'
}
//this is our HTML
<div id="form1"></div>
<script>
Components.Attach("FormValid").to("form1");
</script>
I still think last one inline <script> should be there and it is not mixing logic with representation because this is component - solid piece. It have no meaning one without another. Actually this should be a part of application. Something like html of component(in las one example is div) should be defined and wrapped with component which will automatically add script and ids.
Now. I showed you 2 examples and i will explain why second is too specific. All stuff is in accessibility and performance(and memory leaks). If you will refresh all html of component frequently - it will blink, also you will need to set up all dynamic events back and check everything for memory leaks. But the main problem if JS will fail - your application will show nothing.
So i prefer to have choice between those two:) and use everything on their places.
Check out a site called quince. I am not sure how many patterns here are javascript ui patterns. But this is a pretty good resource for ui patterns
Patterns aren't always language agnostic. A lot of classic design patterns are pointless in JavaScript because we don't need a lot of the workaround that they solve in stricter langauge paradigms.
The reason MVC isn't such a hot fit for client-side web development, however is more situational.
First of all I think time and pain have proven that typical web applications are best treated as two separate applications. The one that happens on the browser and the one that happens on the server. The fewer dependencies you establish between the two, the more flexible, maintainable and easier web apps have been to modify in my experience.
The M is business logic (which people tend to incaccurately conflate with "database layer" IMO).
The problem with MVC in that scenario is that we don't want to expose business logic on the client-side and attempting to munge the whole app into one hideous http-divide-hiding construct has proven painful as I mentioned.
Very similar patterns where you separate data or "view model" concerns can work fairly well, however.

Commonly accepted best practices around code organization in JavaScript [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
As JavaScript frameworks like jQuery make client side web applications richer and more functional, I've started to notice one problem...
How in the world do you keep this organized?
Put all your handlers in one spot and write functions for all the events?
Create function/classes to wrap all your functionality?
Write like crazy and just hope it works out for the best?
Give up and get a new career?
I mention jQuery, but it's really any JavaScript code in general. I'm finding that as lines upon lines begin to pile up, it gets harder to manage the script files or find what you are looking for. Quite possibly the biggest propblems I've found is there are so many ways to do the same thing, it's hard to know which one is the current commonly accepted best practice.
Are there any general recommendations on the best way to keep your .js files as nice and neat as the rest of your application? Or is this just a matter of IDE? Is there a better option out there?
EDIT
This question was intended to be more about code organization and not file organization. There has been some really good examples of merging files or splitting content around.
My question is: what is the current commonly accepted best practice way to organize your actual code? What is your way, or even a recommended way to interact with page elements and create reuseable code that doesn't conflict with each other?
Some people have listed namespaces which is a good idea. What are some other ways, more specifically dealing with elements on the page and keeping the code organized and neat?
It would be a lot nicer if javascript had namespaces built in, but I find that organizing things like Dustin Diaz describes here helps me a lot.
var DED = (function() {
var private_var;
function private_method()
{
// do stuff here
}
return {
method_1 : function()
{
// do stuff here
},
method_2 : function()
{
// do stuff here
}
};
})();
I put different "namespaces" and sometimes individual classes in separate files. Usually I start with one file and as a class or namespace gets big enough to warrant it, I separate it out into its own file. Using a tool to combine all you files for production is an excellent idea as well.
I try to avoid including any javascript with the HTML. All the code is encapsulated into classes and each class is in its own file. For development, I have separate <script> tags to include each js file, but they get merged into a single larger package for production to reduce the overhead of the HTTP requests.
Typically, I'll have a single 'main' js file for each application. So, if I was writing a "survey" application, i would have a js file called "survey.js". This would contain the entry point into the jQuery code. I create jQuery references during instantiation and then pass them into my objects as parameters. This means that the javascript classes are 'pure' and don't contain any references to CSS ids or classnames.
// file: survey.js
$(document).ready(function() {
var jS = $('#surveycontainer');
var jB = $('#dimscreencontainer');
var d = new DimScreen({container: jB});
var s = new Survey({container: jS, DimScreen: d});
s.show();
});
I also find naming convention to be important for readability. For example: I prepend 'j' to all jQuery instances.
In the above example, there is a class called DimScreen. (Assume this dims the screen and pops up an alert box.) It needs a div element that it can enlarge to cover the screen, and then add an alert box, so I pass in a jQuery object. jQuery has a plug-in concept, but it seemed limiting (e.g. instances are not persistent and cannot be accessed) with no real upside. So the DimScreen class would be a standard javascript class that just happens to use jQuery.
// file: dimscreen.js
function DimScreen(opts) {
this.jB = opts.container;
// ...
}; // need the semi-colon for minimizing!
DimScreen.prototype.draw = function(msg) {
var me = this;
me.jB.addClass('fullscreen').append('<div>'+msg+'</div>');
//...
};
I've built some fairly complex appliations using this approach.
You can break up your scripts into separate files for development, then create a "release" version where you cram them all together and run YUI Compressor or something similar on it.
Inspired by earlier posts I made a copy of Rakefile and vendor directories distributed with WysiHat (a RTE mentioned by changelog) and made a few modifications to include code-checking with JSLint and minification with YUI Compressor.
The idea is to use Sprockets (from WysiHat) to merge multiple JavaScripts into one file, check syntax of the merged file with JSLint and minify it with YUI Compressor before distribution.
Prerequisites
Java Runtime
ruby and rake gem
You should know how to put a JAR into Classpath
Now do
Download Rhino and put the JAR ("js.jar") to your classpath
Download YUI Compressor and put the JAR (build/yuicompressor-xyz.jar) to your classpath
Download WysiHat and copy "vendor" directory to the root of your JavaScript project
Download JSLint for Rhino and put it inside the "vendor" directory
Now create a file named "Rakefile" in the root directory of the JavaScript project and add the following content to it:
require 'rake'
ROOT = File.expand_path(File.dirname(__FILE__))
OUTPUT_MERGED = "final.js"
OUTPUT_MINIFIED = "final.min.js"
task :default => :check
desc "Merges the JavaScript sources."
task :merge do
require File.join(ROOT, "vendor", "sprockets")
environment = Sprockets::Environment.new(".")
preprocessor = Sprockets::Preprocessor.new(environment)
%w(main.js).each do |filename|
pathname = environment.find(filename)
preprocessor.require(pathname.source_file)
end
output = preprocessor.output_file
File.open(File.join(ROOT, OUTPUT_MERGED), 'w') { |f| f.write(output) }
end
desc "Check the JavaScript source with JSLint."
task :check => [:merge] do
jslint_path = File.join(ROOT, "vendor", "jslint.js")
sh 'java', 'org.mozilla.javascript.tools.shell.Main',
jslint_path, OUTPUT_MERGED
end
desc "Minifies the JavaScript source."
task :minify => [:merge] do
sh 'java', 'com.yahoo.platform.yui.compressor.Bootstrap', '-v',
OUTPUT_MERGED, '-o', OUTPUT_MINIFIED
end
If you done everything correctly, you should be able to use the following commands in your console:
rake merge -- to merge different JavaScript files into one
rake check -- to check the syntax of your code (this is the default task, so you can simply type rake)
rake minify -- to prepare minified version of your JS code
On source merging
Using Sprockets, the JavaScript pre-processor you can include (or require) other JavaScript files. Use the following syntax to include other scripts from the initial file (named "main.js", but you can change that in the Rakefile):
(function() {
//= require "subdir/jsfile.js"
//= require "anotherfile.js"
// some code that depends on included files
// note that all included files can be in the same private scope
})();
And then...
Take a look at Rakefile provided with WysiHat to set the automated unit testing up. Nice stuff :)
And now for the answer
This does not answer the original question very well. I know and I'm sorry about that, but I've posted it here because I hope it may be useful to someone else to organize their mess.
My approach to the problem is to do as much object-oriented modelling I can and separate implementations into different files. Then the handlers should be as short as possible. The example with List singleton is also nice one.
And namespaces... well they can be imitated by deeper object structure.
if (typeof org === 'undefined') {
var org = {};
}
if (!org.hasOwnProperty('example')) {
org.example = {};
}
org.example.AnotherObject = function () {
// constructor body
};
I'm not big fan of imitations, but this can be helpful if you have many objects that you would like to move out of the global scope.
The code organization requires adoption of conventions and documentation standards:
1. Namespace code for a physical file;
Exc = {};
2. Group classes in these namespaces javascript;
3. Set Prototypes or related functions or classes for representing real-world objects;
Exc = {};
Exc.ui = {};
Exc.ui.maskedInput = function (mask) {
this.mask = mask;
...
};
Exc.ui.domTips = function (dom, tips) {
this.dom = gift;
this.tips = tips;
...
};
4. Set conventions to improve the code. For example, group all of its internal functions or methods in its class attribute of an object type.
Exc.ui.domTips = function (dom, tips) {
this.dom = gift;
this.tips = tips;
this.internal = {
widthEstimates: function (tips) {
...
}
formatTips: function () {
...
}
};
...
};
5. Make documentation of namespaces, classes, methods and variables. Where necessary also discuss some of the code (some FIs and Fors, they usually implement important logic of the code).
/**
* Namespace <i> Example </i> created to group other namespaces of the "Example".
*/
Exc = {};
/**
* Namespace <i> ui </i> created with the aim of grouping namespaces user interface.
*/
Exc.ui = {};
/**
* Class <i> maskdInput </i> used to add an input HTML formatting capabilities and validation of data and information.
* # Param {String} mask - mask validation of input data.
*/
Exc.ui.maskedInput = function (mask) {
this.mask = mask;
...
};
/**
* Class <i> domTips </i> used to add an HTML element the ability to present tips and information about its function or rule input etc..
* # Param {String} id - id of the HTML element.
* # Param {String} tips - tips on the element that will appear when the mouse is over the element whose identifier is id <i> </i>.
*/
Exc.ui.domTips = function (id, tips) {
this.domID = id;
this.tips = tips;
...
};
These are just some tips, but that has greatly helped in organizing the code. Remember you must have discipline to succeed!
Following good OO design principals and design patterns goes a long way to making your code easy to maintain and understand.
But one of the best things I've discovered recently are signals and slots aka publish/subscribe.
Have a look at http://markdotmeyer.blogspot.com/2008/09/jquery-publish-subscribe.html
for a simple jQuery implementation.
The idea is well used in other languages for GUI development. When something significant happens somewhere in your code you publish a global synthetic event which other methods in other objects may subscribe to.
This gives excellent separation of objects.
I think Dojo (and Prototype?) have a built in version of this technique.
see also What are signals and slots?
I was able to successfully apply the Javascript Module Pattern to an Ext JS application at my previous job. It provided a simple way to create nicely encapsulated code.
Dojo had the module system from the day one. In fact it is considered to be a cornerstone of Dojo, the glue that holds it all together:
dojo.require — the official doc.
Understanding dojo.declare, dojo.require, and dojo.provide.
Introducing Dojo.
Using modules Dojo achieves following objectives:
Namespaces for Dojo code and custom code (dojo.declare()) — do not pollute the global space, coexist with other libraries, and user's non-Dojo-aware code.
Loading modules synchronously or asynchronously by name (dojo.require()).
Custom builds by analyzing module dependencies to create a single file or a group of interdependent files (so-called layers) to include only what your web application needs. Custom builds can include Dojo modules and customer-supplied modules as well.
Transparent CDN-based access to Dojo and user's code. Both AOL and Google carry Dojo in this fashion, but some customers do that for their custom web applications as well.
Check out JavasciptMVC.
You can :
split up your code into model, view and controller layers.
compress all code into a single production file
auto-generate code
create and run unit tests
and lots more...
Best of all, it uses jQuery, so you can take advantage of other jQuery plugins too.
My boss still speaks of the times when they wrote modular code (C language), and complains about how crappy the code is nowadays! It is said that programmers can write assembly in any framework. There is always a strategy to overcome code organisation. The basic problem is with guys who treat java script as a toy and never try to learn it.
In my case, I write js files on a UI theme or application screen basis, with a proper init_screen(). Using proper id naming convention, I make sure that there are no name space conflicts at the root element level. In the unobstrusive window.load(), I tie the things up based on the top level id.
I strictly use java script closures and patterns to hide all private methods. After doing this, never faced a problem of conflicting properties/function definitions/variable definitions. However, when working with a team it is often difficult to enforce the same rigour.
I'm surprised no one mentioned MVC frameworks. I've been using Backbone.js to modularize and decouple my code, and it's been invaluable.
There are quite a few of these kinds of frameworks out there, and most of them are pretty tiny too. My personal opinion is that if you're going to be writing more than just a couple lines of jQuery for flashy UI stuff, or want a rich Ajax application, an MVC framework will make your life much easier.
"Write like crazy and just hope it works out for the best?", I've seen a project like this which was developed and maintained by just 2 developers, a huge application with lots of javascript code. On top of that there were different shortcuts for every possible jquery function you can think of. I suggested they organize the code as plugins, as that is the jquery equivalent of class, module, namespace... and the whole universe. But things got much worse, now they started writing plugins replacing every combination of 3 lines of code used in the project.
Personaly I think jQuery is the devil and it shouldn't be used on projects with lots of javascript because it encourages you to be lazy and not think of organizing code in any way. I'd rather read 100 lines of javascript than one line with 40 chained jQuery functions (I'm not kidding).
Contrary to popular belief it's very easy to organize javascript code in equivalents to namespaces and classes. That's what YUI and Dojo do. You can easily roll your own if you like. I find YUI's approach much better and efficient. But you usualy need a nice editor with support for snippets to compensate for YUI naming conventions if you want to write anything useful.
I create singletons for every thing I really do not need to instantiate several times on screen, a classes for everything else. And all of them are put in the same namespace in the same file. Everything is commented, and designed with UML , state diagrams. The javascript code is clear of html so no inline javascript and I tend to use jquery to minimize cross browser issues.
In my last project -Viajeros.com- I've used a combination of several techniques. I wouldn't know how to organize a web app -- Viajeros is a social networking site for travellers with well-defined sections, so it's kind of easy to separate the code for each area.
I use namespace simulation and lazy loading of modules according to the site section. On each page load I declare a "vjr" object, and always load a set of common functions to it (vjr.base.js). Then each HTML page decides which modules need with a simple:
vjr.Required = ["vjr.gallery", "vjr.comments", "vjr.favorites"];
Vjr.base.js gets each one gzipped from the server and executes them.
vjr.include(vjr.Required);
vjr.include = function(moduleList) {
if (!moduleList) return false;
for (var i = 0; i < moduleList.length; i++) {
if (moduleList[i]) {
$.ajax({
type: "GET", url: vjr.module2fileName(moduleList[i]), dataType: "script"
});
}
}
};
Every "module" has this structure:
vjr.comments = {}
vjr.comments.submitComment = function() { // do stuff }
vjr.comments.validateComment = function() { // do stuff }
// Handlers
vjr.comments.setUpUI = function() {
// Assign handlers to screen elements
}
vjr.comments.init = function () {
// initialize stuff
vjr.comments.setUpUI();
}
$(document).ready(vjr.comments.init);
Given my limited Javascript knowledge, I know there must be better ways to manage this, but until now it's working great for us.
Organising your code in a Jquery centric NameSpace way may look as follows... and will not clash with other Javascript API's like Prototype, Ext either.
<script src="jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var AcmeJQ = jQuery.noConflict(true);
var Acme = {fn: function(){}};
(function($){
Acme.sayHi = function()
{
console.log('Hello');
};
Acme.sayBye = function()
{
console.log('Good Bye');
};
})(AcmeJQ);
// Usage
// Acme.sayHi();
// or
// Say Hello
</script>
Hope this helps.
Good principal of OO + MVC would definitely go a long way for managing a complex javascript app.
Basically I am organizing my app and javascript to the following familiar design (which exists all the way back from my desktop programming days to Web 2.0)
Description for the numeric values on the image:
Widgets representing the views of my application. This should be extensible and separated out neatly resulting good separation that MVC tries to achieve rather than turning my widget into a spaghetti code (equivalent in web app of putting a large block of Javascript directly in HTML). Each widget communicate via others by listening to the event generated by other widgets thus reducing the strong coupling between widgets that could lead to unmanageable code (remember the day of adding onclick everywhere pointing to a global functions in the script tag? Urgh...)
Object models representing the data that I want to populate in the widgets and passing back and forth to the server. By encapsulating the data to its model, the application becomes data format agnostics. For example: while Naturally in Javascript these object models are mostly serialized and deserialized into JSON, if somehow the server is using XML for communication, all I need to change is changing the serialization/deserialization layer and not necessarily needs to change all the widget classes.
Controller classes that manage the business logic and communication to the server + occasionally caching layer. This layer control the communication protocol to the server and put the necessary data into the object models
Classes are wrapped neatly in their corresponding namespaces. I am sure we all know how nasty global namespace could be in Javascript.
In the past, I would separate the files into its own js and use common practice to create OO principles in Javascript. The problem that I soon found that there are multiple ways to write JS OO and it's not necessarily that all team members have the same approach. As the team got larger (in my case more than 15 people), this gets complicated as there is no standard approach for Object Oriented Javascript. At the same time I don't want to write my own framework and repeat some of the work that I am sure smarter people than I have solved.
jQuery is incredibly nice as Javascript Framework and I love it, however as project gets bigger, I clearly need additional structure for my web app especially to facilitate standardize OO practice. For myself, after several experiments, I find that YUI3 Base and Widget (http://yuilibrary.com/yui/docs/widget/ and http://yuilibrary.com/yui/docs/base/index.html) infrastructure provides exactly what I need. Few reasons why I use them.
It provides Namespace support. A real need for OO and neat organization of your code
It support notion of classes and objects
It gives a standardize means to add instance variables to your class
It supports class extension neatly
It provides constructor and destructor
It provides render and event binding
It has base widget framework
Each widget now able to communicate to each other using standard event based model
Most importantly, it gives all the engineers an OO Standard for Javascript development
Contrary to many views, I don't necessarily have to choose between jQuery and YUI3. These two can peacefully co-exist. While YUI3 provides the necessary OO template for my complex web app, jQuery still provides my team with easy to use JS Abstraction that we all come to love and familiar with.
Using YUI3, I have managed to create MVC pattern by separating classes that extend the Base as the Model, classes that extends Widget as a View and off course you have Controller classes that are making necessary logic and server side calls.
Widget can communicate with each other using event based model and listening to the event and doing the necessary task based on predefined interface. Simply put, putting OO + MVC structure to JS is a joy for me.
Just a disclaimer, I don't work for Yahoo! and simply an architect that is trying to cope with the same issue that is posed by the original question. I think if anyone finds equivalent OO framework, this would work as well. Principally, this question applies to other technologies as well. Thank God for all the people who came up with OO Principles + MVC to make our programming days more manageable.
I use Dojo's package management (dojo.require and dojo.provide) and class system (dojo.declare which also allows for simple multiple inheritance) to modularize all of my classes/widgets into separate files. Not only dose this keep your code organized, but it also lets you do lazy/just in time loading of classes/widgets.
A few days ago, the guys at 37Signals released a RTE control, with a twist. They made a library that bundles javascript files using a sort of pre-processor commands.
I've been using it since to separate my JS files and then in the end merge them as one. That way I can separate concerns and, in the end, have only one file that goes through the pipe (gzipped, no less).
In your templates, check if you're in development mode, and include the separate files, and if in production, include the final one (which you'll have to "build" yourself).
Create fake classes, and make sure that anything that can be thrown into a separate function that makes sense is done so. Also make sure to comment a lot, and not to write spagghetti code, rather keeping it all in sections. For example, some nonsense code depicting my ideals. Obviously in real life I also write many libraries that basically encompass their functionality.
$(function(){
//Preload header images
$('a.rollover').preload();
//Create new datagrid
var dGrid = datagrid.init({width: 5, url: 'datalist.txt', style: 'aero'});
});
var datagrid = {
init: function(w, url, style){
//Rendering code goes here for style / width
//code etc
//Fetch data in
$.get(url, {}, function(data){
data = data.split('\n');
for(var i=0; i < data.length; i++){
//fetching data
}
})
},
refresh: function(deep){
//more functions etc.
}
};
Use inheritance patterns to organize large jQuery applications.
I think this ties into, perhaps, DDD (Domain-Driven Design). The application I'm working on, although lacking a formal API, does give hints of such by way of the server-side code (class/file names, etc). Armed with that, I created a top-level object as a container for the entire problem domain; then, I added namespaces in where needed:
var App;
(function()
{
App = new Domain( 'test' );
function Domain( id )
{
this.id = id;
this.echo = function echo( s )
{
alert( s );
}
return this;
}
})();
// separate file
(function(Domain)
{
Domain.Console = new Console();
function Console()
{
this.Log = function Log( s )
{
console.log( s );
}
return this;
}
})(App);
// implementation
App.Console.Log('foo');
For JavaScript organization been using the following
Folder for all your javascript
Page level javascript gets its' own file with the same name of the page. ProductDetail.aspx would be ProductDetail.js
Inside the javascript folder for library files I have a lib folder
Put related library functions in a lib folder that you want to use throughout your application.
Ajax is the only javascript that I move outside of the javascript folder and gets it's own folder. Then I add two sub folders client and server
Client folder gets all the .js files while server folder gets all the server side files.
I'm using this little thing. It gives you 'include' directive for both JS and HTML templates. It eleminates the mess completely.
https://github.com/gaperton/include.js/
$.include({
html: "my_template.html" // include template from file...
})
.define( function( _ ){ // define module...
_.exports = function widget( $this, a_data, a_events ){ // exporting function...
_.html.renderTo( $this, a_data ); // which expands template inside of $this.
$this.find( "#ok").click( a_events.on_click ); // throw event up to the caller...
$this.find( "#refresh").click( function(){
widget( $this, a_data, a_events ); // ...and update ourself. Yep, in that easy way.
});
}
});
You can use jquery mx (used in javascriptMVC) which is a set of scripts that allows you to use models, views, and controllers. I've used it in a project and helped me create structured javascript, with minimal script sizes because of compression. This is a controller example:
$.Controller.extend('Todos',{
".todo mouseover" : function( el, ev ) {
el.css("backgroundColor","red")
},
".todo mouseout" : function( el, ev ) {
el.css("backgroundColor","")
},
".create click" : function() {
this.find("ol").append("<li class='todo'>New Todo</li>");
}
})
new Todos($('#todos'));
You can also use only the controller side of jquerymx if you aren't interested in the view and model parts.
Your question is one that plagued me late last year. The difference - handing the code off to new developers who had never heard of private and public methods. I had to build something simple.
The end result was a small (around 1KB) framework that translates object literals into jQuery. The syntax is visually easier to scan, and if your js grows really large you can write reusable queries to find things like selectors used, loaded files, dependent functions, etc.
Posting a small framework here is impractical, so I wrote a blog post with examples (My first. That was an adventure!). You're welcome to take a look.
For any others here with a few minutes to check it out, I'd greatly appreciate feedback!
FireFox recommended since it supports toSource() for the object query example.
Cheers!
Adam
I use a custom script inspired by Ben Nolan's behaviour (I can't find a current link to this anymore, sadly) to store most of my event handlers. These event handlers are triggered by the elements className or Id, for example.
Example:
Behaviour.register({
'a.delete-post': function(element) {
element.observe('click', function(event) { ... });
},
'a.anotherlink': function(element) {
element.observe('click', function(event) { ... });
}
});
I like to include most of my Javascript libraries on the fly, except the ones that contain global behaviour. I use Zend Framework's headScript() placeholder helper for this, but you can also use javascript to load other scripts on the fly with Ajile for example.
You don't mention what your server-side language is. Or, more pertinently, what framework you are using -- if any -- on the server-side.
IME, I organise things on the server-side and let it all shake out onto the web page. The framework is given the task of organising not only JS that every page has to load, but also JS fragments that work with generated markup. Such fragments you don't usually want emitted more than once - which is why they are abstracted into the framework for that code to look after that problem. :-)
For end-pages that have to emit their own JS, I usually find that there is a logical structure in the generated markup. Such localised JS can often be assembled at the start and/or end of such a structure.
Note that none of this absolves you from writing efficient JavaScript! :-)
Lazy Load the code you need on demand. Google does something like this with their google.loader

Categories