This entry is part 3 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 the previous lesson, we created a Person Class. So if we want to define the same class in backbone js. And that’s what we will be learning in this lesson. “Defining models in Backbone js.” It’s pretty straight forward. Remove the previous code from
main.js and add this code. Take a look on this.
In the above code, we are defining the class and set some default values like for name, age, and occupation.
Fire up the console and fire these commands
Now if checkout chrome we can see a lot of cool awesome things. Type these commands one by one.
We can get all the previous things like to get the name, age or occupation. In backbone js, we do that by using get method
You can’t do things like:
And now you can even update name, or age, etc.
or you can update the values in just on go ie
Set values while initiating object
Another thing can be you can set values while launching, i.e.,
One last point - JSON output
Output on Chrome Console
Let’s take a look how things look like on chrome console.
That’s how you define models in Backbone js. In the next post, let’s add some validations in the model. For example. Age can’t be zero or negative. Or name can’t be blank etc.
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.