I'm starting with Backbone and stumbled upon a question recently. The sample application I'm working on is some kind of playlist. I have a model 'song' and a collection 'Playlist', containing several songs.
The data of the Playlist-collection should be available in multiple views. So my idea is to have global application-variables, and one of these variables could be the Playlist-collection.
This way, I can fetch the songs with the initialization of the app, and access the data in every view of the app.
Below is what I'm doing currently
define(
[
'jQuery',
'Underscore',
'Backbone',
'collections/songlist'
],
function ($, _, Backbone, SonglistCollection)
{
var PlaylistView = Backbone.View.extend({
// properties
el: '#playlist',
collection: new SonglistCollection(),
/**
* Initialize
*/
initialize: function()
{
// load songs
this.collection.on( 'reset' , this.render, this );
this.collection.fetch();
},
/**
* Render
*/
render: function()
{
// loop through the collection and update the view
},
...
);
}
);
And this is my collection
define(
[
'Underscore',
'Backbone',
'models/song'
],
function (_, Backbone, songModel)
{
var songList = Backbone.Collection.extend({
model: songModel,
url: 'song'
});
return songList;
}
);
As you can see, I have to make a new instance of the collection and re-fetch the data for every view where I want to use the data of the Playlist-collection.
Because I'm using require.js, I'm a bit lost about how to create global variables. The way I like to do it is eg. make MyApp.collections.Playlist, but I have no idea how to realize this with AMD (require.js).
Some resources I've already found, but I'm still lost / confused / ...
- Share resources across different amd modules
- http://www.alexrothenberg.com/2011/02/11/backbone.js-makes-building-javascript-applications-fun.html
Thanks a lot in advance!