我不知道我應該採取什麼樣的途徑來使這個代碼的工作「的預期。」 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