Backbone.js
Common Mistakes and Structuring the code
MVC
- Model
- Collection
- View
- Model View
- Collection View
- Template
- Router
General Things
- Do NOT have more than 15 functions inside a class
General
- Do NOT have more than 25 lines inside a function
General
- Do NOT leave any empty functions
Why?
Overwriting the extended properties
General
- Do NOT send any IDs from the front end (eg: UserID, profID)
Model
-
Use it only for data related things
- Do NOT do any other operations
Model
- List out all the properties in the defaults
Model
- Use success and error handlers during fetch / save / delete
- Use Util.Helpers for handling errors
Model / Collection
- Send numerical from the server, not as string
- Use parse function in cases where this ain't possible
- Use parse function to format the data correctly
Model / Collection
- Use the validate method correctly
View
-
For using the options inside view
use _.extend(this.vars, options)
View
- Return the class / View(this) in the render function
View
- Success and Error handlers
- Write separate functions inside the view to handle them
- Bind this functions in _.bindAll(this, ...
View
- Render the html in the view itself
- Do NOT attach the el to DOM outside the view
What generally happens
Now, attach the el to DOM inside the view itself by passing el during initialize
View
- Validate and Sanitize the input with RegEx
- Prevent attacks like XSS
Read more about it
here and about XSS attacks
here
Template
this.$el.html(this.template(this.model.toJSON()));
- Do NOT use any logical / arithmetical or any type of calculation or modification inside the template.
- You CAN use if / else, for, while etc.
Strict NO
Router
- Should contain the list of all the routes
- De-centralize the work of showing the correct view on other views
- To ensure loading up of base view / base data / storyline data only at the start of app - use before function
-
Structuring Backbone code