Backbone.js Example with SoundCloud API

By | May 5, 2013

soundcloud_logo
In this post I am going to elaborate on an example of implementation of the SoundCloud (further SC) API with Backbone.js.
The implementation of the SC API can be done without Backbone.js, but in the process of building a Single Page web application the usage of a MV* library (framwork) is essential.
First off course you will have to have a valid id for the SC API. You can obtain a valid id by registering an app at SC: http://soundcloud.com/you/apps

Then you need to include the SC SDK to your page:

<script src="https://connect.soundcloud.com/sdk.js"></script>

To use the SDK you need to initialize the SDK first:

SC.initialize({
client_id: 'ee8e164717cb8a3495919a9ee68e91fc'
});

In your page you will also have to include backbone.js, and the only dependency that backbone needs, and that is underscore.js. Of cource you will have to use either jQuery, or maybe some other lightweight library:

<script src="js/underscore.js"></script>
<script src="js/jquery.js"></script>
<script src="js/backbone.js"></script>

For our example we will use template, which will be easy accessible through underscore. Here in the template we have ready iframe element, which has an ID varable to be populated from backbone/underscore:

<div class="tracks">
		<script id="trackTemplate" type="text/template">
			<iframe width="100%" height="166" scrolling="no" frameborder="no" src="http://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F<%= id %>&amp;show_artwork=true&amp;auto_play=fals
e&amp;color=00C349&amp;show_comments=false"></iframe>
		</script>
	</div>

As you may know, Backbone.js provides Model, View, Container components, which we extend in our applications.
So, the representation of one track in SC will be our model:

App.Models.Track = Backbone.Model.extend({
validate: function(attrs) {
if ( ! $.trim(attrs.title) ) {
return 'A Track requires a valid title.';
}
},
initialize: function(){
var self = this;
}
});

In the model you can specify defaults if you want, and also put some validations.

The view will be this track attached to the HTML, and the collection will be the tracks for certain Genre.
In the example we will use the genre: House, but this easily can be transformed into a variable an you could be able to get the different tracks.

App.Collections.Tracks = Backbone.Collection.extend({
model: App.Models.Track	

});

The View representation is the tricky part. We will create on View to render each track, and one view that will render the container. For the Tracks representation, it is intuitive to use unnumbered list ‘ul’ and each track to be a list item ‘li’.

App.Views.Tracks = Backbone.View.extend({
tagName: 'ul',
className: 'space-list',
initialize: function(){
_.bindAll(this, "render");
var self = this;
SC.get('/tracks', { genres: 'house', order: 'hotness' }, function(tracks, error) {
if(error) console.log('ERROR: ', error);
_.each(tracks, function(value, index){
                self.collection.add(new App.Models.Track(value));
            });
         self.collection.on("sync", this.render, this);
         self.render();
        }
      
)},

render: function() {	
this.collection.each(this.addOne, this);
return this;
},

addOne: function(track) {
var trackView = new App.Views.Track({ model: track });
this.$el.append(trackView.render().el);
}
});

and finally the View of one track:

App.Views.Track = Backbone.View.extend({
	tagName: 'li',
	className: 'space-list-item',
	template: template('trackTemplate'),

	initialize: function() {	
                
	},

	render: function() {
		var template = this.template( this.model.toJSON() );
		this.$el.html(template);
		return this;
	}
});

You can find the full example at: https://github.com/kuzman/soundcloud-backbone

One thought on “Backbone.js Example with SoundCloud API

  1. adam

    Thanks, this is an awesome little tutorial and thanks again for including the code.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *