我不知道我应该采取什么样的途径来使这个代码的工作“的预期。” API调用是异步的 - 所以构造函数在数据加载之前返回。需要异步API调用数据的构造函数?
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;
});
}
是否有可能强制构造函数不提前返回?理想情况下,我不会要的参数任意量传递到宋构造和带来的只是宋它的范围之外的相关信息..
我认为这是我想要的。让我试试看,一秒钟。 –
'getJSON'回调中的'this'不会引用'Song'实例。 – lanzz
@lanzz哦,是的。我刚刚复制了代码。让我编辑它。 – freakish