Examples of good JavaScript code in open source web apps [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I'm struggling to find a way of writing good JavaScript code that would be efficient, widely accepted by other developers and not very ugly.
Until recently, what I used were just literal objects and bits of jQuery but after reading Douglas Crockford's "JavaScript: The Good Parts" I now fully realize that there's more to JavaScript than AJAX, DOM modifications and simple animation.
The problem is that JavaScript seems not much standarized. The amount of OOP/inheritance patterns available overwhelms me. I'm not used to every framework/library providing its own impementation of inheritance. I also don't want to make a wrong decision regarding such things because this would mean rewriting all the code in case of some problems.
So what I'm looking for are existing open source web applications that use JavaScript heavily, if possible on the client side, to see what patterns are used in real projects. I would like to see the code of web applications, not frameworks or libraries. I don't mind though if those web apps are based on some framework (and if it's Dojo or RequireJS it'll be even better because I'm using them ;)

What I always recommend to anyone who is interested in this kind of thing is: STICK TO WHAT YOUR TEAM DOES. If they use camelCase for methods, you use it. If they use snake_case for variables, you do it. If your team prefers spaces over tabs; use them.
Never go into a stablished team with standardized style changing things because it looks better unless it's causing heavy problems.
If you're not working on a team and you're interested on using a coding style; then use the style of the libraries you use the most.
If you use jQuery stick to jQuery Coding Style Guidelines
If you use Closure Library use JavaScript Google Coding Style
If you use MooTools Library use MooTools Coding Style Guideline
Organization wise, Closure is the best.. but to me somehow it feels like I'm reading JAVA instead of javascript. Go figure.

Yep. There are a few JavaScript gurus that have written alot about how to write JavaScript, about prototype based OOP with JavaScript, even about how indenting and naming variables should be done.
However, if you are looking for a large implementation of JavaScript to study as an example, I would look for HTML5 game implementations. It's practically guaranteed that you will find a large enough, well written example that is not minified.

If you are interested in JavaScript standards I would check out commonJS. They have a lot of good ideas about how JavaScript should be done.
BravoJS is a good module implementation for the browser.
As for examples jQuery's source code was mentioned in the comments. jQuery does a good job but it is I would also check out Narwhal JS for examples of how things should be done.
Here is a good free design patterns book that I found helpful Essential JavaScript And jQuery Design Patterns.
You wont find one solution to your problem and that is how JavaScript is designed. I would recommended experimenting. I find that Douglas Crockford has a lot of great ideas but that does not mean you have to follow him to the letter.

A good project is : http://impactjs.com/
A good reading is : http://addyosmani.com/blog/essentialjsdesignpatterns/

Great question. I couldn't find one example of a well written object oriented open source application. Tiny MCE was so-so, but I wouldn't consider it well written: http://www.tinymce.com/
However, I have written clean, well factored object oriented javascript at work. It's proprietary so I can't share it, but I can explain what worked for me to learn how to do that:
1) Read the mozilla javascript object oriented programming tutorial. Their explanation of javascript inheritance is exactly what google closure uses. Personally I think what Crockford calls pseudo classical is easiest to read and maintain since 4 of the 5 other programming languages I know use classes (java, c#, python, and php. perl's the oddball here with no classes either).
https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript
2) Read the book 'Object Oriented Javascript' by Stoyan Stefanov.
3) Take an existing procedural javascript code base and refactor it to objects. Use the tips in 'Clean Code' by Robert C. Martin as they apply to any programming language.
4) Structure your code so it has many different files similar to how you'd use classes in a language with classes.
5) Implement dependency injection without an IOC container by creating all your objects at a top level and feeding them down into the objects that depend on them.
There's a lot more, but hopefully this is a helpful start.
Here is what I feel is the correct way to implement inheritance in javascript. this is from the google closure library:
goog.inherits = function(childCtor, parentCtor) {
/** #constructor */
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
childCtor.prototype.constructor = childCtor;
};

Coincidentally, today on SlashDot there is a review of the 6th edition of Javascript: The Definitive Guide, which the reviewer there says "retains its crown as the ultimate reference resource for JavaScript programmers." It's 1,100 pages.
Yes, this isn't the sample app you were seeking, but the book does have a lot of examples and advice about best practices.

There are several ways to learn how to write good JS code.
You can read books. The best one about organization of JS code and about common patterns including inheritance is JavaScript Patterns by Stoyan Stefanov.
Another good way to learn is just look through the excellent code of other developers and using it. The best library I've seen from the point of code organization and using of patterns is Google Closure Library. It is used internally by Google in the RIA like Gmail Google Docs.

A kind person in irc suggested this eBook and I found it verry helpful.
Learning JavaScript Design Patterns
A book by Addy Osmani
http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Related

Coffeescript tutorials that don't assume Javascript knowledge

I know I'm coming at this the wrong way. You're supposed to learn Javascript first, then start looking at Coffeescript when you get tired of braces and variable declarations. Me however, I'm a somewhat experienced Ruby and Python programmer but with zero Javascript fluency who looks to get into web scripting (mainly through Rails).
I'm convinced that Coffeescript is the way to go for me, but I'm hard pressed to find a tutorial that does not assume significant Javascript familiarity. Most of the tutorials I have seen explain Coffeescript's peculiarities in detail only to gloss over such minor topics as how to actually write web applications.
So, do you know of any Coffeescript tutorials for people who don't know JS to begin with?
You probably don't want to hear this, but I'm going to say it anyway: you should still learn JavaScript first.
JavaScript is a little unique from other languages, in that it has a monopoly over browser scripting. There is currently no other language that can be used in a browser (unless it uses a plugin, or the interpreter is in JavaScript!). As such, for any project that needs to do any amount of client-side scripting, JavaScript knowledge is a must.
You're probably thinking "Hey, I know Python and Ruby, and I never had to learn C or assembly!", which is of course true. But, those language never had a monopoly over their domain. Python can be used for the same things as C, in many cases. The platform doesn't care what language you use, as long as it supports it.
And the browser platform only support JavaScript.
CoffeScript is an abstraction of JavaScript. Although CoffeeScript is compiled into JavaScript, when you're trying to figure out that obscure JavaScript error, or debug a generated function, or are wondering why there are two levels of unnamed function nesting, you're going to want to know what's really going on.
Now, I'm not saying that you have to become a JavaScript Ninja (although I'd recommend it), but what I am saying is that you should come to grips with the actual web language first.
Learn JavaScript, learn its concepts (it's a very fascinating language, in my opinion, once you get past some of the deficiencies), and then use CoffeeScript to abstract away the technicalities.
Since you did ask for a tutorial, though, here's some: First, the Mozilla guide to JavaScript is quite nice. If you want some more advanced topics, there's also an interactive tutorial made by John Resig. And finally, here's a bunch of CoffeeScript tutorials that you probably already know about.
I suggest the free online Smooth Coffeescript book (based on Eloquent Javascript).
No previous programming knowledge is required. CoffeeScript lets you
write web oriented applications simply and elegantly. It is closely
related to JavaScript but without its quirky corners.
Smooth CoffeeScript is a book about CoffeeScript and programming.
Start with programming fundamentals, learn about functional
programming with Underscore and problem solving, study object
orientation and modularity. It covers client/server web apps with
Canvas and WebSockets.
I had a background in Python, ActionScript and Java. I started directly learning CoffeeScript with no intention of learning JavaScript. I learned a bunch of JavaScript along the way but I think it's perfectly OK to set out to learn CoffeeScript directly.
I was first attracted to Smooth CoffeeScript because it claimed to be targeted at folks trying to learn CoffeeScript directly. However, the style of writing was not to my liking. YMMV.
Besides, with my Python background, I found that I didn't need much help with the syntax. I got all of the syntax help I needed directly from he CoffeeScript web page. I mostly needed help with the platform (cake, development environments, testing, etc.) which is covered quite well on the CoffeeScript web page, and what else I needed I got from a couple of other books. My favorite teaching book is The Little Book on CoffeeScript (read in an hour) and my favorite reference is Trevor Burnham's Pragmatic Bookshelf book on CoffeeScript which taught me jQuery from the CoffeeScript perspective.
Another thing that helped me ramp up quickly was to fork/upgrade a few of my own tools in CoffeeScript. I forked the CoffeeDoc repository on github to create my own version and I eventually re-wrote it to create CoffeeDocTest which is like Python's DocTest except for CoffeeScript. My upgrades to the Coda syntax mode for CoffeeScript were accepted back into the master branch via github's pull-request mechanism... after a code review and some cleanup. Looking at someone else's code really helps you learn the idioms. Getting a code review from someone in the know helps even more.
Your question doesn't make a lot of sense to me because CoffeeScript is JavaScript. To know one is to know the other. It may sound counter-intuitive for me to suggest that the best way to learn CoffeeScript is by cracking open a JavaScript book but the languages are one and the same.
I know they look different, but the differences end at the syntactical layer[1]. Add some semicolons, curly braces and parens to CoffeeScript and you're more or less there. So go and learn JavaScript, and you'll find you're learning CoffeeScript too.
You could also learn CoffeeScript and incidentally pick up JavaScript. This may be a little bit more difficult though, since until source mapping is implemented, debugging can only be done in JavaScript (and you'll be debugging a lot, I assure you ;-)).
[1]: Apart from maybe class definitions which are slightly more complicated.

Advanced JavaScript/JQuery Design Patterns

What are the best resources on Design Patterns catering specifically to web development with JavaScript and JQuery?
I'm particularly interested in information on programming my own libraries, reusable components, widgets, etc. and the merits of various techniques (for instance in the case of components/widgets comparing those employed in jQuery UI vs. rolling your own).
I'm also curious about the intricacies of JavaScript as a programming language, and the finer points of object-based programming with JavaScript.
Big fan of Douglas Crockford and the Yahoo video series. Looking for additional examples.
One very instructional thing you might do is read over the jQuery source code. It's a treasure-trove of interesting and efficient coding techniques. You might then broaden your horizons by reading over the source for Prototype or some other library.
The nice thing about reading good code and trying to understand it is that it's really real; it is the good code, so you bypass a layer of rhetoric.
Similar to Pointy's answer, you should take a look at these two videos, which help you understand the source code of JQuery (it might be difficult for some to dive into the code from start to finish):
10 things I learned from the jquery source
11 more things I learned from the jquery source
Paul Irish, a member of the JQuery team, goes through some very interesting design patterns in the JQuery source in a humorous way. I think he picks some really interesting spots, which really gives you a lot of usable knowledge you can use elsewhere.
It's probably the resource that has given me the most knowledge about a particular field in the shortest time. It's just really valuable.
This guy has some really good stuff as far as the "intricacies of JavaScript as a programming language" part of your question is concerned:
http://devlicio.us/blogs/sergio_pereira/default.aspx
e.g.
http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx
The comp.lang.javascript group on Usenet is an excellent resource: pretty much everything related to browser scripting has been discussed there and is available in the archive, and some of the regulars, while not always the most polite, are incredibly knowledgeable.

Has anyone used JS.Class and liked it?

Has anyone used JS.Class and liked it? I 've used Joose before and find it really good in creating clean code that is very readable and maintainable. Any real life stories about JS.Class?
Sorry for the first-person answer here, but although I have not used JS.Class, from a Java/Javascript developer standpoint, it looks very good. Our team works on a Java project with most of our front end using home-brewed JavaScript (and not a small amount of it). We don't use any JS frameworks (jQuery didn't exist when our project started) and we've even implemented our own drag and drop/sort utilities that make extensive use of inheritance.
For convenience and for the ability to use inheritance, (and through much evolution) we ended up developing methods that come to nearly the exact same patterns as JS.Class (but not nearly as extensive).
Everything I read in the docs on classes and modules, inheritance, etc. seemed very natural — in fact, it looks like we could probably replace all of our class-creation methods (a method we called objectLib.createClass) with new JS.Class with no other changes to make.
We also ended up developing our own Set classes and other array and object utilities that JS.Class includes as part of it's core functionality.
So, while I can't say that I've used JS.Class and liked it, I can say that as a Javascript developer I have needed to solve nearly the exact problems that JS.Class appears to solve very well.
I have not used it and I do not personally find a good use for the classical inheritance pattern so far in my experience. I switched to Javascript programming from Java to run away from all those design patterns!
You may also (if you haven't already) take a look at these posts from Douglas Crockford on what he thinks of classical inheritance in javascript.
http://www.crockford.com/javascript/inheritance.html
http://javascript.crockford.com/prototypal.html

jQuery framework internals

I am trying to understand the internals of how jquery framework is written and finding it hard to understand the code.
Does anyone have any suggestions regarding a good way to get started.
Thanks for all the useful input. Editing the topic since I had limited space for adding individual comments.
I have written a lot of basic javascript code.
I know basic DOM, have used event handlers, know CSS basics. I have read about many of the topics you have mentioned and I am familiar with it although not an expert and have not coded some of the advanced topics like closures. Here are the books I have used so far Head first javascript - good in the beginning as a starter.
Books my friends have recommended and I use regularly are Javascript - The Definitive Guide, Javascript - The good parts (I read this a while ago and it was hard for me at the time).
My friend just recommended Secrets of Javascript Ninja - John Resig. Seems like a good one.
I ordered the Javascript Design patterns book you recommend last week
I have read the https://developer.mozilla.org/en/JavaScript you pointed me to. I will checkout some of the other resources you pointed me to.
Let me think a little more regarding if I want to do a little more reading before I post specific questions I have on jquery.
Thanks
Susan
To comprehend the actual source would require some degree of Javascript knowledge - If you don't already know what's going on then you basically need to learn more Javascript.
Key things to learn:
Prototypal inheritance ( the
inheritance used in ECMAScript, the
core language on which Javascript is
based upon )
Lambdas ( inline functions )
Closures ( outer variables from outer scope accessible from inner functions )
Regular expressions ( used for matching the selector strings fed to jQuery )
DOM ( The DOM API which is used to interact with markup languages )
When learning, use Firebug so you can evaluate your expressions interactively and immediately see what's going on
An excellent free resource for learning that I would recommend:
http://eloquentjavascript.net/contents.html
If you're a beginner to DOM Scripting/Javascript:
http://www.amazon.com/DOM-Scripting-Design-JavaScript-Document/dp/1590595335/ref=sr_1_19?ie=UTF8&s=books&qid=1252905196&sr=1-19
If you're intermediate level:
http://www.amazon.com/gp/product/0596517742/ref=s9_simz_gw_s0_p14_i3?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-2&pf_rd_r=0KCJ77GKHPREBFD3WAKG&pf_rd_t=101&pf_rd_p=470938631&pf_rd_i=507846
If you're past intermediate level and want to be an expert:
http://www.amazon.com/Professional-JavaScript-Developers-Wrox-Guides/dp/0764579088
http://www.amazon.com/Pro-JavaScript-Techniques-John-Resig/dp/1590597273/ref=sr_1_10?ie=UTF8&s=books&qid=1252905139&sr=1-10
http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X/ref=sr_1_16?ie=UTF8&s=books&qid=1252905196&sr=1-16
Other technical references:
http://www.w3.org/DOM/
http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf
https://developer.mozilla.org/en/JavaScript
If you have specific questions about a certain code snippet just ask here. Another resource that I can recommend for more advanced questions would be the jQuery mailing list or irc://irc.freenode.net/jquery where jresig hangs out himself and comes by and answers questions. There are other guru ops who reside there like ajpiano/paulirish/nlogax.
If you're looking for insight about how jQuery is written, the uncompressed source code is pretty readable. There are a few books mentioned in SO74884 that are worth a read. Resig's book doesn't really cover jQuery at all, but is good about teaching object oriented javascript.
If you are having a problem understanding something in jQuery's code (why it was done/how it works), you should post a question with some code bits to Stack Overflow, asking for some help understanding it.
Why not learn from the man himself, John Resig, here : http://ejohn.org/apps/learn/
Based on that, I'd definitely get the book your friend suggested.
You can also find some more nice resources on his website, courtesy of googling site:ejohn.org/apps
I was also like you interested in how jQuery works internally, I've spent some time learning from jQuery code source and trying to understand the core architecture, then I've created a github repo how-jQuery-works to share my knowledge that I've acquired with other developers, hope you learn something from this repository.

Object Oriented Javascript

In the course of programming we encounter large javascript files which are open source and written in an object oriented manner( like JQuery ).
If we need to modify these files we have to have a basic knowledge of the members and the flow. If we have multiple files then the task is much more difficult.
Where do I start to get the flow of this??
First of all I think that you have to understand how JavaScript object orientation works, JavaScript OO is Prototype-based, in which classes are not present, and behavior reuse is implemented by prototyping.
I've seen that this can be hard to catch at the beginning for programmers that have been working on conventional class-based object-oriented languages (like C++, C#, Java, etc).
Recommended articles:
Introduction to Object-Oriented JavaScript
JavaScript: The World's Most Misunderstood Programming Language
Classical Inheritance in JavaScript
Private Members in JavaScript
Class-Based vs. Prototype-Based Languages
There are two things I would do:
Read. If there's documentation files, read those. If there's comments, read those. If neither of those help you, then go to the source and read that.
When you talk about open source Javascript, I assume you mean this JS is collected into some kind of project; all client-side JS is open source :P. In that case, the authors may be willing to tell you about their code. Locate their email on the project page, and ask them to give you a high-level overview of the code so you can start reading it and understanding it yourself. They probably won't be willing to hold your hand through the entire thing, but having that as a starting point would probably help.
I have a copy of
Javascript: The Good Parts
and
Javascript: The Definitive Guide
sitting on my desk right now. Incidentally these are the only two Javascript books which Douglas Crockford thinks are any good ;)
They'll teach you how Javascript works, specifically how its object model is different to most (but not all) other object-oriented languages.
Other than that, do check out all the articles on Crockford's website, as have already been mentioned in other answers.
I agree with allyourcode there's no magic trick. You have to read the code and read the docs. And if the docs are no good, maybe you should think about using a different framework.
A good start is in understanding the difference between traditional OO and Javascript's Prototype model. (Crockford has some articless that implement traditional OO for Javascript in order to contrast the behaviors.)

Categories

Resources