Organizing Your Backbone.js Application With Modules
weblog.bocoup.com
weblog.bocoup.com
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.
Be smart about your code, you can expose anything you want and attach anything to the module object for testing.
In general: http://backbonejs.org/#FAQ-tim-toady
There are plenty of libraries doing this already.
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.