I’m going to start my blogging here at Iora by starting a little series on “best practices” we’ve discovered while building applications with Backbone.js. Since my web series on behavior driven development is already named “YOU’RE DOING IT WRONG” I think I’d like to focus a little bit more on the positive. Backbone is such a new framework that we’re all going to make mistakes here and there, but we should strive to learn and apply some solid development principles.
As a light intro to this series, I’d like to talk about a practice that I’ve started using on the view layer. I’ve begun explicitly naming each object passed into a view initializer instead of using the available ‘model’ object. Let me demonstrate with a bit of code:
1 2 3 4 5 6 7 8 9 10
This would be instantiated with a router something along these lines:
1 2 3 4 5 6 7 8 9 10 11
The generally accepted pattern for Backbone.js development is to instead use the model object, saving yourself the initialization step. Being slightly more explicit helps out as you expand functionality to the views. Let’s say we want to add the user’s most recent post:
1 2 3 4 5 6 7 8 9 10 11 12
If we went with the path of least resistance the implementation could be this instead:
1 2 3 4 5 6 7
This certainly does get the job done, but I’m not convinced it is more readable code. Furthermore, I’m encouraged to continue to use the this.options to render additional objects passed in, which smells of a Law of Demeter violation to me. Of course, this is a pretty small and insignificant code example, this pattern becomes increasingly valuable when you have a chain of composite views.