I've been looking into BackboneJS for quite sometime now and thought it would interesting to build an application using the MVC pattern. Although Backbone provides various components - Models, Collections, Routers and Views; it doesn't provide a framework that can help you to structure the application using these components. While working on this application, I realized that I can separate these components in such a way that they can be made reusable or rather loosely coupled by defining the components in separate files. However, there was an interesting problem that I came across where the Views had a dependency on the Collections to be loaded first and then render the template data. I had read a little about RequireJS that allowed modules to be loaded asynchronously and also in resolving dependency. Thought I would give it a try and see whether it addresses this problem.
This is how I've structured my application:
/project /css bootstrap.css /scripts /app /Collections NavbarCollection.js /Router ApplicationRouter.js /Templates header.js navbar.js /Views HeaderView.js HomePageView.js NavbarView.js /lib backbone.js bootstrap-dropdown.js jquery.js require.js text.js underscore.js main.js index.html
Coming to applying MVC to the application, I have structured the directory in such a way that it is easy to maintain and build on top of it. Here's a picture of how the application would work:
The Views can then render it by getting the html from the template and compiling it with the data that has been received from the server. The generated code would then be rendered on the specified container. One thing to note here is that I'm using Underscore's templating engine to render the views. I prefer using underscore since Backbone already has a dependency on it and also the fact that it comes with several utility functions. However, one could use any other templating engine to render the generated content on the page.
I've created a simple application that shows static data as well as data returned from the collection. The page has a static header and a Navbar that is constructed by fetching the data from the collection. You can open the console view and see how RequireJS invokes the dependent modules before rendering the data.
You can refer to the source code here: https://github.com/sagar-ganatra/frontendMVC