我想知道我应该采取什么途径使这段代码“按预期”工作。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;
});
}
是否可以强制构造函数不过早返回?理想情况下,我不必将任意数量的参数传递给 Song 构造函数,并将仅与 Song 相关的信息带到它的范围之外..