I'm wondering what route I should take to make this code work "as intended." The API call is asynchronous -- so the constructor returns before data is loaded.
addSongById: function (songId) {
var song = new Song(songId);
console.log(song);
this.addSong(song);
if (this.songCount() == 1)
this.play();
UserInterface.refresh();
SongGrid.reload();
},
function Song(songId) {
$.getJSON('http://gdata.youtube.com/feeds/api/videos/' + songId + '?v=2&alt=json-in-script&callback=?', function (data) {
this.id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); });
this.songId = songId;
this.url = "http://youtu.be/" + songId;
this.name = data.entry.title.$t;
});
}
Is it possible to force the constructor to not return prematurely? Ideally I wouldn't have to pass an arbitrary amount of parameters into the Song constructor and bring information only relevant to Song outside the scope of it..