PageRenderTime 52ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/_posts/2011-10-10-organizing-backbone-using-modules.md

https://github.com/donskifarrell/backbonetutorials
Markdown | 430 lines | 339 code | 91 blank | 0 comment | 0 complexity | 6be8d8bc780eee12e57ffbccdd892467 MD5 | raw file
  1. ---
  2. layout: post
  3. title: Organizing your application using Modules (require.js)
  4. type: intermediate
  5. posturl: http://backbonetutorials.com/organizing-backbone-using-modules
  6. ---
  7. # Organizing your application using Modules (require.js)
  8. Unfortunately Backbone.js does not tell you how to organize your code, leaving many developers in the dark regarding how to load scripts and lay out their development enviroments.
  9. This was quite a different decision to other Javascript MVC frameworks who were more in favor of setting a development philosophy.
  10. Hopefully this tutorial will allow you to build a much more robust project with great separation of concerns between design and code.
  11. This tutorial will get you started on combining Backbone.js with [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) (Asynchronous Module Definitions).
  12. ## What is AMD?
  13. [Asynchronous Module Definitions](https://github.com/amdjs/amdjs-api/wiki/AMD) designed to load modular code asynchronously in the browser and server. It is actually a fork of the Common.js specification. Many script loaders have built their implementations around AMD, seeing it as the future of modular Javascript development.
  14. This tutorial will use [Require.js](http://requirejs.org) to implement a modular and organized Backbone.js.
  15. **I highly recommend using AMD for application development**
  16. Quick Overview
  17. * Modular
  18. * Scalable
  19. * Compiles well(see [r.js](http://requirejs.org/docs/optimization.html) )
  20. * Market Adoption( [Dojo 1.6 converted fully to AMD](http://dojotoolkit.org/reference-guide/releasenotes/1.6.html) )
  21. ## Why Require.js?
  22. p. Require.js has a great community and it is growing rapidly. [James Burke](http://tagneto.blogspot.com/) the author is married to Require.js and responds to user feedback always. A leading expert in script loading, he is also a contributer to the AMD specification.
  23. <a href="https://twitter.com/jrburke" class="twitter-follow-button">Follow @jrburke</a>
  24. <script src="//platform.twitter.com/widgets.js" type="text/javascript"></script>
  25. ## Getting started
  26. To easily understand this tutorial you should jump straight into the example code base.
  27. [Example Codebase](https://github.com/thomasdavis/backbonetutorials/tree/gh-pages/examples/modular-backbone)
  28. [Example Demo](http://backbonetutorials.com/examples/modular-backbone)
  29. The tutorial is only loosely coupled with the example and you will find the example to be more comprehensive.
  30. If you would like to see how a particuliar use case would be implemented please visit the Github page and create an issue.(Example Request: How to do nested views).
  31. The example isn't super fleshed out but should give you a vague idea.
  32. ## Example File Structure
  33. There are many different ways to lay out your files and I believe it is actually dependent on the size and type of the project. In the example below views and templates are mirroed in file structure. Collections and Models aren't categorized into folders kind of like an ORM.
  34. {% highlight javascript %}
  35. /* File Structure
  36. ├── imgs
  37. ├── css
  38. │ └── style.css
  39. ├── templates
  40. │ ├── projects
  41. │ │ ├── list.html
  42. │ │ └── edit.html
  43. │ └── users
  44. │ ├── list.html
  45. │ └── edit.html
  46. ├── js
  47. │ ├── libs
  48. │ │ ├── jquery
  49. │ │ │ ├── jquery.min.js
  50. │ │ │ └── jquery.js // jQuery Library Wrapper
  51. │ │ ├── backbone
  52. │ │ │ ├── backbone.min.js
  53. │ │ │ └── backbone.js // Backbone Library Wrapper
  54. │ │ └── underscore
  55. │ │ │ ├── underscore.min.js
  56. │ │ │ └── underscore.js // Underscore Library Wrapper
  57. │ ├── models
  58. │ │ ├── users.js
  59. │ │ └── projects.js
  60. │ ├── collections
  61. │ │ ├── users.js
  62. │ │ └── projects.js
  63. │ ├── views
  64. │ │ ├── projects
  65. │ │ │ ├── list.js
  66. │ │ │ └── edit.js
  67. │ │ └── users
  68. │ │ ├── list.js
  69. │ │ └── edit.js
  70. │ ├── router.js
  71. │ ├── app.js
  72. │ ├── main.js // Bootstrap
  73. │ ├── order.js //Require.js plugin
  74. │ └── text.js //Require.js plugin
  75. └── index.html
  76. */
  77. {% endhighlight %}
  78. To continue you must really understand what we are aiming towards as described in the introduction.
  79. ## Bootstrapping your application
  80. Using Require.js we define a single entry point on our index page.
  81. We should setup any useful containers that might be used by our Backbone views.
  82. _Note: The data-main attribute on our single script tag tells Require.js to load the script located at "js/main.js". It automatically appends the ".js"_
  83. {% highlight html %}
  84. <!doctype html>
  85. <html lang="en">
  86. <head>
  87. <title>Jackie Chan</title>
  88. <!-- Load the script "js/main.js" as our entry point -->
  89. <script data-main="js/main" src="js/libs/require/require.js"></script>
  90. </head>
  91. <body>
  92. <div id="container">
  93. <div id="menu"></div>
  94. <div id="content"></div>
  95. </div>
  96. </body>
  97. </html>
  98. {% endhighlight %}
  99. You should most always end up with quite a light weight index file. You can serve this off your server and then the rest of your site off a CDN ensuring that everything that can be cached, will be.
  100. ### What does the bootstrap look like?
  101. Our bootstrap file will be responsible for configuring Require.js and loading initially important dependencies.
  102. In the below example we configure Require.js to create shortcut alias to commonly used scripts such as jQuery, Underscore and Backbone.
  103. Due to the nature of these libraries implementations we actually have to load them in order because they each depend on each other existing in the global namespace(which is bad but is all we have to work with).
  104. Hopefully if the AMD specification takes off these libraries will add code to allow themselves to be loaded asynchronously. Due to this inconvience the bootstrap is not as intuitive as it could be, I hope to solve this problem in the near future.
  105. We also request a module called "app", this will contain the entireity of our application logic.
  106. _Note: Modules are loaded relativly to the boot strap and always append with ".js". So the module "app" will load "app.js" which is in the same directory as the bootstrap._
  107. {% highlight javascript %}
  108. // Filename: main.js
  109. // Require.js allows us to configure shortcut alias
  110. // There usage will become more apparent futher along in the tutorial.
  111. require.config({
  112. paths: {
  113. jQuery: 'libs/jquery/jquery',
  114. Underscore: 'libs/underscore/underscore',
  115. Backbone: 'libs/backbone/backbone'
  116. }
  117. });
  118. require([
  119. // Load our app module and pass it to our definition function
  120. 'app',
  121. // Some plugins have to be loaded in order due to there non AMD compliance
  122. // Because these scripts are not "modules" they do not pass any values to the definition function below
  123. 'order!libs/jquery/jquery-min',
  124. 'order!libs/underscore/underscore-min',
  125. 'order!libs/backbone/backbone-min'
  126. ], function(App){
  127. // The "app" dependency is passed in as "App"
  128. // Again, the other dependencies passed in are not "AMD" therefore don't pass a parameter to this function
  129. App.initialize();
  130. });
  131. {% endhighlight %}
  132. ## How should we lay out external scripts?
  133. Any modules we develop for our application using AMD/Require.js will be asynchronously loaded.
  134. We have a heavy dependency on jQuery, Underscore and Backbone, unfortunatly this libraries are loaded synchronously and also depend on each other existing in the global namespace.
  135. Below I propose a solution(until these libraries allow themselves to be loaded asynchronously) to allow these libraries to be loaded properly(synchronously) and also removing themselves from global scope.
  136. {% highlight javascript %}
  137. // Filename: libs/jquery/jquery.js
  138. define([
  139. // Load the original jQuery source file
  140. 'order!libs/jquery/jquery-min'
  141. ], function(){
  142. // Tell Require.js that this module returns a reference to jQuery
  143. return jQuery;
  144. });
  145. {% endhighlight %}
  146. {% highlight javascript %}
  147. // Filename: libs/underscore/underscore
  148. // As above lets load the original underscore source code
  149. define(['order!libs/underscore/underscore-min'], function(){
  150. // Tell Require.js that this module returns a reference to Underscore
  151. return _;
  152. });
  153. {% endhighlight %}
  154. {% highlight javascript %}
  155. // Filename: libs/backbone/backbone
  156. // Finally lets load the original backbone source code
  157. define(['order!libs/backbone/backbone-min'], function(){
  158. // Now that all the orignal source codes have ran and accessed each other
  159. // We can call noConflict() to remove them from the global name space
  160. // Require.js will keep a reference to them so we can use them in our modules
  161. _.noConflict();
  162. $.noConflict();
  163. return Backbone.noConflict();
  164. });
  165. {% endhighlight %}
  166. ## A boiler plate module
  167. So before we start developing our application, let's quickly look over boiler plate code that will be reused quite often.
  168. For convience sake I generally keep a "boilerplate.js" in my application root so I can copy it when I need to.
  169. {%highlight javascript %}
  170. //Filename: boilerplate.js
  171. define([
  172. // These are path alias that we configured in our bootstrap
  173. 'jQuery', // lib/jquery/jquery
  174. 'Underscore', // lib/underscore/underscore
  175. 'Backbone' // lib/backbone/backbone
  176. ], function($, _, Backbone){
  177. // Above we have passed in jQuery, Underscore and Backbone
  178. // They will not be accesible in the global scope
  179. return {};
  180. // What we return here will be used by other modules
  181. });
  182. {% endhighlight %}
  183. The first argument of the define function is our dependency array, we can pass in any modules we like in the future.
  184. ## App.js Building our applications main module
  185. Our applications main module should always remain quite light weight. This tutorial covers only setting up a Backbone Router and initializing it in our main module.
  186. The router will then load the correct dependencies depending on the current URL.
  187. {% highlight javascript %}
  188. // Filename: app.js
  189. define([
  190. 'jQuery',
  191. 'Underscore',
  192. 'Backbone',
  193. 'router', // Request router.js
  194. ], function($, _, Backbone, Router){
  195. var initialize = function(){
  196. // Pass in our Router module and call it's initialize function
  197. Router.initialize();
  198. }
  199. return {
  200. initialize: initialize
  201. };
  202. });
  203. {% endhighlight %}
  204. {% highlight javascript %}
  205. // Filename: router.js
  206. define([
  207. 'jQuery',
  208. 'Underscore',
  209. 'Backbone',
  210. 'views/projects/list',
  211. 'views/users/list'
  212. ], function($, _, Backbone, Session, projectListView, userListView){
  213. var AppRouter = Backbone.Router.extend({
  214. routes: {
  215. // Define some URL routes
  216. '/projects': 'showProjects',
  217. '/users': 'showUsers',
  218. // Default
  219. '*actions": 'defaultAction'
  220. },
  221. showProjects: function(){
  222. // Call render on the module we loaded in via the dependency array
  223. // 'views/projects/list'
  224. projectListView.render();
  225. },
  226. // As above, call render on our loaded module
  227. // 'views/users/list'
  228. showUsers: function(){
  229. userListView.render();
  230. },
  231. defaultAction: function(actions){
  232. // We have no matching route, lets just log what the URL was
  233. console.log('No route:', actions);
  234. }
  235. });
  236. var initialize = function(){
  237. var app_router = new AppRouter;
  238. Backbone.history.start();
  239. };
  240. return {
  241. initialize: initialize
  242. };
  243. });
  244. {% endhighlight %}
  245. ## Modularizing a Backbone View
  246. Backbone views most usually always interact with the DOM, using our new modular system we can load in Javascript templates using Require.js text! plugin.
  247. {% highlight javascript %}
  248. // Filename: views/project/list
  249. define([
  250. 'jQuery',
  251. 'Underscore',
  252. 'Backbone',
  253. // Using the Require.js text! plugin, we are loaded raw text
  254. // which will be used as our views primary template
  255. 'text!templates/project/list.html'
  256. ], function($, _, Backbone, projectListTemplate){
  257. var projectListView = Backbone.View.extend({
  258. el: $('#container'),
  259. render: function(){
  260. // Using Underscore we can compile our template with data
  261. var data = {};
  262. var compiledTemplate = _.template( projectListTemplate, data );
  263. // Append our compiled template to this Views "el"
  264. this.el.append( compiledTemplate );
  265. }
  266. });
  267. // Our module now returns an instantiated view
  268. // Sometimes you might return an un-instantiated view e.g. return projectListView
  269. return new projectListView;
  270. });
  271. {% endhighlight %}
  272. Javascript templating allows us to seperate the design from the application logic placing all our html in the templates folder.
  273. ## Modularizing a Collection, Model and View
  274. Now we put it altogether by chaining up a Model, Collection and View which is a typical scenairo when building a Backbone.js application.
  275. First off we will define our model
  276. {% highlight javascript %}
  277. // Filename: models/project
  278. define([
  279. 'Underscore',
  280. 'Backbone'
  281. ], function(_, Backbone){
  282. var projectModel = Backbone.Model.extend({
  283. defaults: {
  284. name: "Harry Potter"
  285. }
  286. });
  287. // You usually don't return a model instantiated
  288. return projectModel;
  289. });
  290. {% endhighlight %}
  291. Now we have a model, our collection module can depend on it. We will set the "model" attribute of our collection to the loaded module. Backbone.js offers great benefits when doing this.
  292. > Collection.model: Override this property to specify the model class that the collection contains. If defined, you can pass raw attributes objects (and arrays) to add, create, and reset, and the attributes will be converted into a model of the proper type.
  293. {% highlight javascript %}
  294. // Filename: collections/projects
  295. define([
  296. 'Underscore',
  297. 'Backbone',
  298. // Pull in the Model module from above
  299. 'models/project'
  300. ], function(_, Backbone, projectModel){
  301. var ProjectCollection = Backbone.Collection.extend({
  302. model: projectModel
  303. });
  304. // You don't usually return a collection instantiated
  305. return ProjectCollection;
  306. });
  307. {% endhighlight %}
  308. Now we can simply depend on our collection in our view and pass it to our Javascript template.
  309. {% highlight javascript %}
  310. // Filename: views/projects/list
  311. define([
  312. 'jQuery',
  313. 'Underscore',
  314. 'Backbone',
  315. // Pull in the Collection module from above
  316. 'collections/projects',
  317. 'text!templates/projects/list
  318. ], function(_, Backbone, ProjectsCollection, projectsListTemplate){
  319. var projectListView = Backbone.View.extend({
  320. el: $("#container"),
  321. initialize: function(){
  322. this.collection = new ProjectsCollection;
  323. this.collection.add({ name: "Ginger Kid"});
  324. // Compile the template using Underscores micro-templating
  325. var compiledTemplate = _.template( projectsListTemplate, { projects: this.collection.models } );
  326. this.el.html(compiledTemplate);
  327. }
  328. });
  329. // Returning instantiated views can be quite useful for having "state"
  330. return new projectListView;
  331. });
  332. {% endhighlight %}
  333. ## Conclusion
  334. Looking forward to feedback so I can turn this post and example into quality references on building modular Javascript applications.
  335. Get in touch with me on twitter, comments or github!
  336. ### Relevant Links
  337. * [Organizing Your Backbone.js Application With Modules](http://weblog.bocoup.com/organizing-your-backbone-js-application-with-modules)
  338. ### Contributors
  339. * [Jakub Kozisek](https://github.com/dzejkej) (created modular-backbone-updated containing updated libs with AMD support)