On the backend, web development frameworks have been growing quickly in popularity. Rails, Django, CakePHP, and others are popular because they save developers a ton of time. Someone once said that a good developer is a lazy developer, and frameworks enable developers to kick back with a Corona on a beach (well, not quite, but close) by making a lot of the architectural decisions for the developer. Rails is a great example of this, with a clear MVC structure, preset file system hierarchy, and even database schema conventions. If you were coding a site in pure Ruby, you’d need to make all of these decision yourself.
window object. As client-side applications are get larger, this is completely unsustainable. It makes code hard to maintain, hard to understand, and un-testable with unit testing libraries. Backbone.js greatly helps with all of these issues.
Backbone dos and don’ts
- Put most of your front-end application (or business) logic in the models. This is basically the same thing you would do with a MVC app on the server.
- Use a templating library. Underscore.js has a pretty decent
- Try using the Rails asset pipeline or some other way to minify and compile your JS. This way, you can spread your Backbone code out into many files. I tended to use a folder hierarchy similar to Rails (folders for models, collections, controllers, and views).
- Put much logic in your views. It is very hard to debug view code because the function that renders the view is typically created programmatically by the templating library.
- Don’t prematurely optimize your view code. The easiest way to render a view is to just create an HTML fragment from a templating library then insert it into the DOM with jQuery. This is fine for most cases. You can also manipulate the DOM by changing the inner text of elements on a view re-render, which might be faster but often isn’t worth the extra work.