What are your best practices for backbone.js projects?

fbuchinger picture fbuchinger · Apr 4, 2011 · Viewed 11.3k times · Source

Although I'm following backbone.js for some months and worked through a plethora of tutorials, I'm still not confident enough in backbone (or my skills regarding it) to use it in a larger project.

My experience is that the backbone.js tutorials vary greatly in quality, some are terribly outdated (especially the sample todo app from the backbone docs).

So I'd like to know about your backbone.js best practices/recipes? How do you handle nested collections/views? JSON serialisation? More complex queries between models?

Answer

Vlad Gurovich picture Vlad Gurovich · Apr 8, 2011

Here is a list of questions you seem to have asked:

backbone.js best practices/recipes
My number one practice/recipe is to dive into the backbone.js code and read it, step through it with js debugger even. The code is well documented and is an excellent example of what modern JS code should be.

How do you handle nested collections/views?
Afaik there is no "simple way" to handle nested collections and handling events that happen in a sub-collection. You'd have to implement it. I haven't had to deal with a collection of collections yet though, so maybe you can avoid it by restructuring your "data model". A model that has a collection of models in itself satisfies most of the requirement of a nested model.

As far as views go, you're basically in control how they get rendered. A view as provided by backbone is nothing but a mechanism to get changes in corresponded model to your render code. You implement the rendering. So if you want nested views, you can use template engine that supports partials(If i understand correctly what you mean by nested views).

JSON serialisation
Whats your question? The backbone doc says "it's highly recommended to include json2.js"

More complex queries between models?
Again, whats your question? Backbone provides you structure to do your own thing, you have to implement the complexities yourself

Relations between models
Again, you are implementing the models. Your models can contain other models. What you do with them and how you interact is up to you. In my experience its wasn't necessary to replicate the backend data model in javascript. Its quite possible that your front-end models will be simpler than the backend ones.

Model inheritance
By using backbone.js you are already using model inheritance. This is what happens when you write var MyModel = Backbone.Model.extend...

Sorry for not going into more detail, but like Thomas Davis said, the questions were very vague. You'd get more detailed answer on a more detailed question describing a specific problem you're having.