I am using require.js with backbone and backbone.localstorage and I am trying to figure out how to make use of the data after calling fetch, not sure how to go about it... I am trying to pass the data into my view and make use of it.
Here is the example of the data stored in localstorage:
[{"artist":"Hits 1 Entertainment 4-1-1","title":"Hear Katy's Perry's New Album!"}, ...]
So it is objects within an array.
This is my code for backbone...
var songz = new Songs();
songz.localStorage = new Backbone.LocalStorage("music");
songz.fetch({dataType: 'json'});
var songV = new SongV({collection: songz});
songV.render();
Songs is a collection, that looks like this in the collections file, SongV is the view for each song.
Here is the view with the code above included:
define([
'jquery',
'underscore',
'backbone',
'models/song',
'collections/songs',
'views/song',
'text!templates/page.html'
], function($, _, Backbone, Song, Songs, SongV, PageT){
var Page = Backbone.View.extend({
el: $("#page"),
render: function () {
this.$el.html( PageT );
var songz = new Songs();
songz.localStorage = new Backbone.LocalStorage("music");
songz.fetch({dataType: 'json'});
var songV = new SongV({collection: songz});
songV.render();
}
});
return Page;
});
Here is the collection file:
define([
'jquery',
'underscore',
'backbone',
'models/song',
], function($, _, Backbone, Song){
var Songs = Backbone.Collection.extend({
model: Song,
initialize: function () {
}
});
return Songs;
});
Here is the model file:
define([
'underscore',
'backbone'
], function(_, Backbone) {
var Song = Backbone.Model.extend({
});
return Song;
});
Here is the template file:
<tr>
<th> Number </th>
<th> Title </th>
<th> Artist </th>
<th> Date_Added </th>
<th> Video </th>
</tr>
<% _.each(songs, function(song){ %>
<tr>
<td> <%= song.get("number") %> </td>
<td> <%= song.get("title") %> </td>
<td> <%= song.get("artist") %> </td>
<td> <%= song.get("added_on") %> </td>
<td> <%= song.get("video") %> </td>
</tr>
<% }); %>
You need to fetch and then bind to the reset event on the collection to see when it was successfully pulled the data from the server.
This is how Backbone.LocalStorage stores the collections and models --> here
See the table at the bottom, the key for the chain block is you local storage name and then each model has a unique key.
So this means if you have data sitting in local storage that you have put there yourself, you should take it out with a cross-browser local storage device like store.js and then use it to populate your Backbone.Collection.
Alternatively, you could fetch from the server (recommended) and that will populate your collection. Or you could bootstrap the data on page load and reset your collection that way.