- Easy scripting debugging and indentification.
- Good practices.
- Useful and easy implementation.
- Easy to test.
Preparing our app
We’re going to prepare our app to use my approach.
To remove it from a Ruby on Rails app, we must:
- Remove turbolinks gem from our Gemfile.
- Remove the line //= require turbolinks from our application.js
- Remove data-turbolinks-track attributes from our application layout application.html.slim (if you’re using slim)
Organize our layout
Add Backbone and its dependencies
There are different ways to get BackboneJS and its dependecies.
Once got BackboneJS and its dependencies, add them to our app.
- Add them to application.js
Note: i prefer to use Lo-dash instead UnderscoreJS
Structure our code
We’re going to see how to organize our files and folders.
- A folder to storage the controllers.
- Folders for storage the models and collections.
- A folder to storage the views.
I place the main files as routes.js and app.js in the root folder. I also add subfolder if I want to use modules.
Our base app
We’re going to define our aplication namespace in a file (app.js). It‘ll save the parts of our app such as models, views, collections and controllers.
The BackboneJS models might be used for information storage, using an object oriented structure. You can use them with their pairs in the server side or like a pieces of “page” as BackboneJS use in its webpage.
The BackboneJS collections might be used to store a group of models.
We’re going to use the BackboneJS views to organize our page behavior. You can chose between two ways to organize them.
- As event controller
As an example, we could have in different part of our app a modal to accept or decline something. We need to handle the server response when an User accept or decline. If it accept, the modal should disappear or display an error message otherwise.
- As template render
You can get an example of this in the BackboneJS website because it’s the most used.
Here, you can see the first example:
We’re going to use an object to structure our code better. In those ones, we’re going to define functions which will be used in the routes.
Those functions could be used to instantiate views, make operations, make calls to server, fill models or collections and for another useful thing that I forget.
We’re going to use the BackboneJS routes to specify where our script should be ran. This feature is optional but highly recommended. We can use the BackboneJS views only, but the routes is better than an overload of conditionals and instantiated elements.
To define them we must use Backbone.Routes. Once defined we need to storage that in a variable.
We’re going to enable pushState option to avoid the Hash # usage in the URL.
As seen above, we can use BackboneJS for organize the scripts of a Ruby on Rails app.
Thanks for read my article and IMHE (experience). I hope you can add some comments here, they’re important for me.