So I have a problem with my jquery applications entirely. When the application is small it's cool. But when it is quite large it is such a mess.. Nested functions, ajax calls, selectors, dom manipulations. Seems like it's non-containable at all, especially when it has a complex logic.
The functional approach does not help me out much. And I don't see how to use classes and inheritance here in practice. How to organize the code? I have read a lot of articles about prototypical and pseudo classical inheritance but they just explain how things works, like how you can inherit 'Person' from 'Human' or something like this. How can I actually use it in real life?
I find two things that really help organize javascript. One use objects for encapsulation ( http://www.dustindiaz.com/namespace-your-javascript ), and two, write a library for common tasks. The normal refactoring strategies work for javascript, extract functions, commonize, if you have 4 functions doing nearly the same thing, change them to a single function which can handle all four cases.
When planning a large jQuery application that I'm currently working on, I found this post by Addy Osmani very useful.
Full disclosure, though: we ended up hanging most of our application backbone off of a YUI3 core. All our "controller" code is written in jQuery, but the frontend data model is YUI3.
Related
I've been looking at frameworks to help me write better structured JS code and came across Backbone. It seems to have lots of functionality for creating classes with public and private properties and members, inheritance, etc.
Angular JS seems to do a load of completely different stuff like automatic binding of markup to model and lots of clever trickery for templating, filtering, sorting etc.
My question is not which should I choose, but is it sensible to use both? AngularJS looks really cool, but unless I'm missing something then it doesn't seem to provide any OO stuff for you to work with. Does this make sense?
I'm not sure that pairing Angular with another framework would really make a lot of sense, it's quite complete as it is.
Backbone on the other hand is more composable, for instance you might take a look at the Knockback project, which make Backbone and KnockoutJS work together quite nicely. Knockout takes a MVVM approach which is relatively close to what you'll find in Angular.
If you need to write OO for your data (aka Models), just use a library like Base.js. It gives you nice OO syntax, inheritance, with methods like extend. The good part is that it keeps the getter syntax like myObject.var so it plays nicely with Angular, contrarily to Backbone where you need to use a getter myObject.get('var'), so data bindings works just fine.
To understand the difference and the reason between those syntaxes and philosophy, read one of the Angular author's answer here in SO.
AngularJS purposely does not impose any particular inheritance style, so you're free to do whatever you want. If you like Backbone.js's inheritance model, you can use underscore (which is included in Backbone.js) to provide the .extend helper.
I was full time java developers, now I also work on JavaScript. couple of years back when I started learning JavaScript, first library I tried was jquery like most of the people. But it made my life harder, and after sometime I started writing fairly large JavaScript app. It wasn't coming together for me using jquery. I had huge codebase without much of a structure. It was method blocks updating HTML blocks using selectors.
Then I tried mootools and obliviously as a java developer it appealed to me a lot. And I was able to write managible web apps having huge code base.
As per my understanding Mootools is not considered a preferred way to write JavaScript because it mimic conventional OO over default prototype-based OO language. So now to really understand javascript and desire of walking with the world, i decided to try other approaches, so again I turned back to jquery, and realise that only jquery is not enough. So started looking at current trending frameworks like backbone, spine, ember.js, sprouteCore. Strangly I found that these frameworks at their core tries to mimic conventional OO like mootools only by having constructors and creating a object of class and reusing this class object to create instance objects. So
Am I missing something?
Is mootools way really wrong?
Mootools project is very alive and releases new versions/features, but I don't
see many people talking about it on Internet, also there are no comparisions vs backbone/spine etc.
As per my understanding Mootools is not considered a preferred way to write JavaScript because it mimic conventional OO over default prototype-based OO language.
Where do you get that from? The greatest thing about javascript is that is so loosely typed (see what I did there) - you can write the same thing in a platitude of ways. There are also so many ways to abstract it and repackage it - and this applies from a simple new Array() vs [] to how you structure your app.
If you love JavaScript (or just know it and secretly hate it), you will be fine with MooTools. The API is mostly either native js or ES5 spec or - rarely - an extra utility that also feels 'natural'. The notable exception that stands out is Class. And the fact that you can abstract having to deal with prototypical inheritance by passing an object to a special constructor Type function that returns your instance is ... oh wait. It looks different but what it does pretty much sounds like normal javascript. Only easier -- why wouldn't you prefer that?
A lot is being made these days of the clientside MVC boom and this 'new way of developing apps'. Suddenly, jQuery folks were given the luxury of tap water! I have spoken to a lot of MooTools developers over this and (un)surprisingly discovered that most think MooTools rarely needs anything like that. I tend to agree with them. The only gaping hole is a view controller with templating but there are a fair few solutions.
The thing is, you cannot directly compare a MVC framework with MooTools, it is not the same. At all. You can compare the so called Model constructors vs Classes.
I have now spent a while researching various MVC framework solutions and patterns to see if our new app can be moulded into a 'best practice' shape.
Basically, I tried backbone.js (with and w/o a mootools adapter) and found it awkward to use after MooTools - it felt like a step back. When I say use I don't mean I can't use it but it feels awkward to extend and build on. I am sure it's just down to experience, though, have yet to read all the backbone patterns examples out there.
Typical issue I run into - wanted to have a special Model property that tells it to use localStorage to fetch/save. Not obvious how - examples tend to show you can either route Backbone.sync to one or the other but not both at the same time. I had to actually decorate the function and extend it, keeping the original referenced in case the model did not require localStorage. NOT the best / most obvious pattern to maintain and leaves me dependent on their changes not breaking my code.
In MooTools, I would have just extended my Model class and could have defined a custom Class Mutator property (like Binds or Implements). Done. Write what you know, they say, and not for nothing...
Another issue - it's tightly coupled with data and you cannot reuse models like classes - eg, a User model loads a user and renders through a User Edit view. You then want to create a new customer and suddenly, you cannot reuse the old object that easily and just render the same view but with empty values. I think it will also be down to inexperience on my part or bad architecture.
Ember.js I found slightly more moo-ish as an interface though It did not quite click either. Frankly, backbone was less trouble to setup.
There are other attempts. Composer is one - once again for mootools but it tries too hard to be backbone and is written by people that are relatively new to the framework so I would not call it mature. Knockout etc etc. There's a new one every day, literally.
Garrick Cheung released a framework called Neuro which has huge potential.
I wrote Epitome - a full MVP implementation based upon classes and events and wrapped in AMD modules, feel free to check it out. It also comes with a builder, documentation builder and many little goodies to get you started.
SeanMonstar released Shipyard, which is used by Mozilla Flight Deck - http://seanmonstar.github.com/Shipyard/. Whereas it's not native mootools, it's mootools-ish with mootools class etc - only w/o extending natives, so a great alternative.
BTW, try irc.freenode.net #mootools or the mail list and you will always get a good answer.
Anyway, enough on MVC. The points about MooTools have been made countless of times. Haters will be haters. Those that love it don't look back. If you are a programmer from an OOP background or are looking for something that renders itself well to patterns, do yourself a favour and stick with it. Exciting times are ahead. Roadmap for 1.5: AMD, for 2.0 (aka, Prime) Host object prototyping optional. These have been the two biggest talking-down points in the eyes of critics. No more 'dirty' prototypes so people can get on with using for ... in loops incorrectly on non-objects and without hasOwnProperty checks. Anyway...
Other things to worry about may be of importance. Like, the size of the 'community'. I think having a healthy community is a great thing but even if you look at jquery, the amount of actual contributors vs users is low. The ratio of quality CODE vs good looking effects is bad. The plugins you can use - a lot are not well written or dead and unsupported. When you draw the line, it's a lot less glamorous than you'd think!
I am not saying that mootools or other frameworks don't have these problems. It is fair to say MooTools people and especially the core devs are fairly private and less vocal about what they do. It may send the wrong impressions, I don't know. It certainly is no jQuery.
Ultimately - if you have the resources and the know-how, use what works best and what will scale. There are even these that use coffeescript and swear by it. Who am I to judge...
In the interests of full disclosure - you will find it MUCH harder to find a decent mootools dev when you recruit. Cannot be ignored...
Compared with Java/C#/C/C++ projects, we often see web frontend projects (html/css/javascript) are too complex to read and maintain. So, can we summarize some best practices for web frontend projects? The goal is readability, modularization, easy to maintain.
Accomplishing this takes a mix of good patterns and knowing what fights not to fight.
CSS is best if it's factored out, efficient, and cleanly formatted. No overthinking necessary here, CSS is a beautiful language, I like to keep it simple. For example see my answer here: MVC 3, CSS, Razor and Visual Studio 2010
Javascript can definitely be organized by using some kind of object based pattern: http://www.klauskomenda.com/code/javascript-programming-patterns/. I use something close to "Custom Objects" from that link. With YUI we have built in namespaces, with jQuery we can add them: Is it possible to create a namespace in jQuery?. As far as separating out content, separate objects and related functionality in their own javascript files and include them on the pages where they're needed. For optimization, you can compile all the scripts on any page down into one script. YUI 3 has a great dependency loading mechanism - use that. For jQuery, you can use one of the many dependency loaders: Javascript loaders with jQuery
As far as HTML, I think MVC is the most popular patter these days. Using any modern mvc framework will lay things out for you well. (Ex. rails, any java ones, asp.net mvc, pylons, etc.)
Well, for now, web development has many approaches and there's no standard way of doing things.
By the way, since JavaScript doesn't support some OOP features like actual classes or namespacing, but prototyping, you need to know that this isn't a good start for crearting good and large moduralized front-end Web projects.
Although there're limitations, you can use prototyping in order to leverage some kind of pseudo-OOP design. That's you can create a component-oriented user interface based on inheritance of some abstract hierarchy defining common behaviors and visualizations.
Keeping in mind one of most important points in any modern development is reuse and scalability, I think using pseudo-OOP with prototyping should be fine to avoid bad practices and enforce maintainibility, readability and moduralization.
For example, you can simulate namespacing with prototypes. This is achieved by creating anonymous objects where their members are anonymous functions acting as getters (properties) where their return type is the prototype of some actual "class" - there're other ways to achieve this same result -:
http://www.codeproject.com/KB/scripting/jsnamespaces.aspx
Or you can simulate polymorphism:
http://www.codeproject.com/KB/scripting/edujini_007_JavaScript_OO.aspx
I could add more references, but I believe you got it: it's more like trying to export actual OOP approaches to JavaScript and use same design patterns that have been in the ground for a lot of years!
Another point should be you can get this moduralization by extending existing JavaScript frameworks like jQuery, Prototype, MooTools, Microsoft AJAX (this is a good start because it has many built-in OOP features like namespaces, inheritance, polymorphism...).
I am a newbie to JavaScript and programming in general. I've started creating my first web app and I would like to rewrite it using an object oriented approach. I've read some articles and book chapters on object oriented JS about how to simulate namespaces, the module pattern and so, but I am having a hard time thinking about how to organize my code inside objects, hope you can help me with this or point me in the right direction to some examples or best practices.
I was thinking to organize it sort of like jQuery with a namespace (called app maybe) and all my app functions inside it, for example app.func1, app.func2, however I have other functions which are used inside those which are like utilities and I would like them to have another name, maybe something like app.util.func... Also my code creates custom objects inside my app, but I don't know where is the right place to put them and their constructors inside my namespace.
Any suggestions, ideas, best practices, templates, or examples on how to organize object oriented javascript? Examples on creating simple library like code would be great.
Thanks in advance!
I've read some articles and book chapters on object oriented JS about how to simulate namespaces, ...
I wouldn't simulate classical OO paradigms in JavaScript. You should stick with what's natural for JavaScript.
Don't do classical inheritance. Use prototypal inheritance or no inheritance at all: Composition/decoration look a lot nicer than inheritance in JavaScript.
You don't need namespaces. They cause unnecessary indirection and cause enterprisey code clutter. Use a good module pattern that hides your functions and variables inside closures.
Try a module loader like RequireJS. You can hide your modules in their own files and closures and let RequireJS do dependency injection magic for you.
Organizing JS application files is a very broad topic. You could organize your classes based on separation of concerns by using paradigms like MVC or MVP. In terms of project organization, building your application on Maven (and following its conventions) could be an option.
Since your question has been at a very high level, I just wanted to throw in some ideas and keywords that you may want to Google and read up on. Maybe after some research and trials and tribulations, you can come back and ask about more specific problems.
Hey guys. There has been a lot of activity lately on the jQuery Dev Group about prototypal inheritance and plugin namespacing, and I want to see who has the best answer for it.
Group link:
http://groups.google.com/group/jquery-dev/browse_thread/thread/620c6a18a16d9665
Questions:
What do you guys think should be done about this and why?
Do you agree with any opinions there? Why or why not?
Why it is important:
If jQuery did decide to implement something like this into the core, this is a huge decision that will affect a lot of people and may affect how they use/extend jQuery and if they continue to use jQuery. It may convert a lot of people to jQuery.
I think what sets jQuery apart from libraries like prototype is that it concentrates on features such as fast DOM selection, traversal and manipulation rather than adding 'flavor' to javascript.
Problem with Prototype is it puts a ruby hat on javascript and it ends up getting bloated with features you probably never end up using.
I have worked in projects where people overuse prototype Classes to implement everything as a class where it simply wasn't needed. People who move from Java or C# (or even Ruby) like to do everything their way - which is often not needed.
I think that this is important step for jQuery. Of cause jQuery is very dom centric lbrary. And that is why it achieves so much attention over the world, but it is hard to build complex solutions basing on it only. You can not use all the benefits of OOP and so you must to have all the code in a head - all of your programmers must. I suppose jQuery is the most easy solution - thats why everybody likes it, but now it wants to be enterprise solution.
I think this can make enterprise client side development faster and that is great:)