One of the good things about Backbone.js is it doesn’t tell us how to do things. It leaves it for us to decide what are the best practices for writing views (or any components).
This is also one of the worst things about Backbone. it makes it almost too easy to take the wrong path, and write views that will be hard to maintain.
The principle we should follow when writing a view is to keep it encapsulated, and keep it as “dumb” as possible – a view should know only the bare minimum it needs to know in order to do it’s job, and do bare minimum it has to do.
Here are 3 simple tips that can help us achieve this:
In my previous post, I covered the structure of a Backbone.js application using RequireJS.
The next thing (or if you are a TDD fan, the first thing) we do is to run some tests on it.
According to Coda Hale:
Writing tests for your code may not reduce the number of bugs, but it will make fixing the bugs you inevitably find easier.
Obviously, we can take advantage of the AMD architecture, to help us write modular tests (or “specs” in the BDD language).
To get a better sense of the challenges and different approaches in unit testing, I wrote the exact same tests three times using three different testing frameworks: Jasmine, Mocha and QUnit.
Backbone gives us a very powerful set of tools. It gives us models, views, and routes – all event driven, consistent and beautifully embrace underscore.js functionality. Being a library rather than a framework, Backbone doesn’t give us application structure. That “glue” we need too initialize the app and glue all the pieces together.
Since coding is by far easier than explaining, I programmed a Todos app in order to demonstrate how this can be done with Asynchronous Module Definition (AMD) using RequireJS.