Explaining views in backbone js - Learning Backbone Js
This entry is part 5 of 14 in the series for A Complete Guide for Learning Backbone Js
- Introduction and Installation
- Representing your data in javascript
- Defining Models in backbone js
- Adding Validations in models backbone js
- Explaining views in backbone js
- How to use templates in backbone js
- How to improve templates in backbone js
- Collections in backbone js
- Collection views in backbone js
- Template helpers in backbone js
- How to use namespace in backbone js
- How to handle dom events in backbone js and define your custom events (Live Demo)
- Routing in backbone js
Agenda
In previous lessons, we saw how to define models and add validations. In this lesson, we will be checking out views in Backbone js. Views are basically how you display your data.
What we have till now
To make things simpler let’s remove validations and functions from the model. So we have this.
So now we want to add a view for a person. For simplicity, let’s take about list items. So every person will be displayed in a li
tag. To define that view lets create a person view, i.e.,
Fire up the console and fire these commands
By default tagName is div
. Here we specified it to use li
. So if we see this output:
Output on Chrome Console
Let’s head back to chrome developer tools and see what we have in this object.
Adding HTML elements like class, id
You can also add other things like cs class name, element id, etc. using some other attributes like
Rendering the view
So backbone offers constructor for the views, i.e., known as initializing, i.e., it will be automatically called when you initiate a view.
Backbone also provides a method render that will render out the output for the data of the model associated with that view. ie
So let’s add all these in out class, so we have something like this:
So in the above code, we defined certain things.
- initialize function that will call on PersonView initialization.
- render method that adds the content in the view
- initialize function is calling render method which will add content in view.
Fire up the console and fire these commands
Let’s head towards Chrome console and execute these commands to see what we have.
Output on Chrome Console
Here is what we have on console:
Problem in the thought process.
I hope you got an idea. But the problem with this code is definition of render method, i.e.,
As our views get complexed like having images and other things. This will become messy. We are lucky that backbone js has templates for that. So let’s head to the new lesson templates in backbone js.
Source code
If you are facing any issues. Check out the source code files at github. I will be creating more and more directories in the same repo regarding each post. Still, if you have any doubts you can comment on the blog post itself, and I will try to reply back asap.