Soundcloud Javascript API SC.get()不允许我更改函数之外的变量 [英] Soundcloud Javascript API SC.get() will not allow me to change a variable outside of the function

查看:98
本文介绍了Soundcloud Javascript API SC.get()不允许我更改函数之外的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎在Soundcloud Javascript API中遇到了SC.get函数的问题。我尝试将一个新项目推送到newSounds数组;但是,在_.each循环退出后,newSounds对象仍然是一个长度为0的数组。此外,在loadSounds执行后声音对象未定义。一些帮助将不胜感激,如果我需要发布更多帮助解决问题,请告诉我。

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();


推荐答案

在这种情况下,棘手的是 SC.get 很可能是异步的,所以当你返回 newSounds 时,它几乎肯定是空的/不完整的。最重要的是,有多个要管理的 SC.get 的调用。

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.

使用<$ c $在jQuery中c> deferred 对象,你可以解决你的问题像这样的问题(灵感来自 http://www.tentonaxe.com/index.cfm/2011/9/22/Using-jQuerywhen-with-a-dynamic-number-of-objects ):

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;
}

这篇关于Soundcloud Javascript API SC.get()不允许我更改函数之外的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆