

Organizing Your Backbone.js Application With Modules - gobhit
http://weblog.bocoup.com/organizing-your-backbone-js-application-with-modules

======
Pewpewarrows
My only issue with doing the full-on module pattern is that, coming from a
Python/Ruby background, I've stopped caring about the notion of private vs
protected vs public, especially when considering testing. In other languages
(like Java) I can add a dash of reflection magic in my unit-tests to get to
hidden components, but that seems to be impossible using Javascript's module
pattern. Take this snippet for example:

    
    
        var Module = (function() {
            var baz;
        
            function foo(x) {
                baz = x;
            }
        
            return {
                bar: function() {
                    foo(42);
                }
            };
        })();
    

There are several variations of the pattern, but that's the basic gist of it.
Once it becomes non-trivial, how do I test foo? How do I verify baz's state?
Furthermore, if I wanted to extend this with one of Javascript's sub-class
implementations, how would my new slightly-different "bar" be able to use
"foo"?

Besides my general opinion of private variables and methods being unnecessary,
unless someone has a good fix for those two problems, I'll never consider
using the module pattern in any code that I write.

~~~
tbranyen
This pattern uses an immediately invoked function expression (IIFE) to scope
dependencies and shorten variable names.

Be smart about your code, you can expose anything you want and attach anything
to the module object for testing.

------
jashkenas
One handy thing to remember for this is that Backbone.js is a library, not a
framework ... you call it, it doesn't call you. If you already have a good
method of organizing, namespacing and loading your JavaScript, you should be
able to get your Models and Views to play along nicely.

In general: <http://backbonejs.org/#FAQ-tim-toady>

------
clarkdave
I've had a great experience using <http://brunch.io> to organise Backbone
applications. Separates everything out as this article suggests and adds a
nice entry point to get started from. It's not as lightweight as organising
things on your own, as it introduces CoffeeScript and Stylus into the mix. If
you're happy with these technologies though it works quite well.

------
fooyc
CommonJS / AMD anyone ?

There are plenty of libraries doing this already.

~~~
tbranyen
I am working on a follow up post, where you will see how complicated these
systems get. Its not trivial nor foundational for anyone looking on how to
structure a project.

Edit: There is a pull request that would make using at least
jQuery/Backbone/Underscore easier to use together, but it has n't been pulled
yet. Writing posts on stuff that just works, is better than trying to convince
developers to hand write wrappers for every lib they want to include.

