Getting started with backbone.js
After viewing a few terms on Google trends it appears that backbone.js is still popular these days. So as such I will commit to writing a few posts on it, and as always with this sort of thing, it will require a getting started type post.
Backbone hello world
So now that I have a work environment together, there is the concept of a stupid simple hello world example, just for the sake of, well getting started. So my first backbone project will be a hello world project in my demos folder.
So in my demos folder I will have a hello_world.html file that will look like this:
and a hello_world.js file that will look like this:
Now that I have a hello world example, a next step might be to get up to speed on how to deal with templates in backbone. Because I am using underscore there is the _.template method in underscore that can be used to create a template, and then I can just pass an object to that template.
As such I can write the line in my render method like this:
Or better yet I can define a template in the View, so then my View can look like this then:
Having a model
Check out my full post on backbone Models
Whenever I start to make a project that is a little advanced there is a desire to separate code that has to do with the state, and manipulation of a model, from code that displays data from that model. This is of course one of the main reasons why I would bother to use something like backbone.
So making a Model in backbone involves using Backbone.Model.extend to create a constructor function that can be used to make one or more instances of that model. For this post I will make a quick Model that stores a hardCoded message, and a current message that is based off that hard coded message, and a current index.
A Model should at the very least have a set method that will be called once to set up the instance of the method when a new instance is created with the new keyword.
Add an event In My View
So now that I have found out how to make a basic hello world view, and a Model, now I would like to find a way to tie everything together. To not just have a Model by itself, but also a View that can be used to work with that Model.
To do this first I need to restructure my html to something where I have a container, and separate display, and input elements inside that container.
Now of course I will need to make many changes to my View from before:
This is my first post on backbone, I was glad that I was able to get down that basics pretty quick. When I have more content on backbone, I will likely add a whats next section to this post, and have some more demos.