This entry is part 5 of 14 in the series for A Complete Guide for Learning Backbone Js
- Introduction and Installation
- 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
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.
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.,
By default tagName is
div. Here we specified it to use
li. So if we see this output:
Let’s head back to chrome developer tools and see what we have in this object.
You can also add other things like cs class name, element id, etc. using some other attributes like
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.
Let’s head towards Chrome console and execute these commands to see what we have.
Here is what we have on console:
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.
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.