We've actually written enough code at this point to test things out. Head to http://localhost:3000
in your browser and pop open a JavaScript console; I prefer Chrome and the Developer tools but use whatever you want. Now try the following lines:
var posts = new Posts(); posts.length // => 0
We can create a Posts
collection instance; as you can see, it's empty by default. We can load the data from the server by running the following line:
posts.fetch();
A collection instance's fetch
method will send a GET request to the server (in fact, if your in-browser tools allow you to see a network request, you'll see a GET request to /posts
). It will merge the models that it receives from the server with the ones already in the collection. Give a second to get a response and then run the following lines:
posts.length // => 1 var post = posts.get(1); post.get("title"); // Lorem Ipsum
Every collection instance has a get
method; we pass it an ID and it will return the model instance with that ID (note that this is the id
field from the database, and not the index number in the collection). Then, each model instance has a get
method that we can use to get properties.