问题
I seem to be having a issue with the SC.get function in the Soundcloud Javascript API. I try to push a new item to the newSounds array; however, after the _.each loop exits the newSounds object is still an array with length = 0. In addition the sounds object is undefined after loadSounds executes. Some help would be greatly appreciated, and if I need to post more to help solve the problem let me know.
loadSounds = function() {
var newSounds = [];
_.each(trackURLs, function(trackURL) {
console.log(trackURL);
SC.get(trackURL, function(track) {
console.log(track.artwork_url);
newSounds.push(track);
});
});
return newSounds;
};
var sounds = loadSounds();
回答1:
The tricky thing in this case is that SC.get
is most likely asynchronous, so when you go to return newSounds
it will almost certainly be empty/incomplete. On top of that, there are multiple calls to SC.get
to manage.
Using the deferred
object in jQuery, you could solve your problem like this (inspired by http://www.tentonaxe.com/index.cfm/2011/9/22/Using-jQuerywhen-with-a-dynamic-number-of-objects):
function loadSounds() {
var newSounds = [];
var deferredObjects = $.map(trackURLs, function (item, index) {
var deferred = $.Deferred();
SC.get(trackURL, function(track) {
newSounds.push(track);
deferred.resolve(track);
});
return deferred.promise();
});
$.when.apply(this, deferredObjects).then(function () {
console.log('All done');
console.log(newSounds);
});
return newSounds;
}
来源:https://stackoverflow.com/questions/14615831/soundcloud-javascript-api-sc-get-will-not-allow-me-to-change-a-variable-outsid