Why the variable is out of scope?

梦想与她 提交于 2019-12-12 05:01:10

问题


I'm having some "weird" issue with my code. It's mostly in Spanish but I'm sure you will get.

$('#favoritos').live( 'pagecreate',function(event){
    var favoritos = false;
    var fav_bus = '';
    var fav_bici = '';
    if (!isLocalStorageAvailable()) // Si no hay Local Storage para qué queremos entrar aqui
        $.mobile.changePage('#errorFavoritos', { transition: "pop" });
    else{
        $.each(localStorage, function(index){
            var itemKey = localStorage.key(index);
            if (itemKey.indexOf('fav')){ // Si es un favorito
                var splitted = itemKey.split('-');
                var tipo = splitted[0];
                var numero = splitted[2];
                favs_locales[itemKey] = {
                    'numero' : numero,
                    'id' : itemKey
                };
                if (tipo == 'bus'){
                    favoritos = true;
                    fav_bus = '<div data-role="collapsible>' +
                                '<h3>Parada ' + numero+ '</h3>' +
                                    '<ul data-role="listview" data-inset="true" id="'+itemKey+'">';
                    pedirTiempos(numero).pipe(formatearTiempos).done(function(html){
                        fav_bus += html + '</ul></div>';
                    });
                }
            }
        });
        // Ya tenemos los datos formateados
        console.log(fav_bus);
        if (fav_bus != ''){
            $('#contentFavoritos').append(
                                '<h3 style="text-align: center;">Paradas de Bus</h3>' +
                                    '<div data-role="collapsible-set">' +
                                        fav_bus +
                                    '</div>');
        }
    }
});

The issue comes in this function:

pedirTiempos(numero).pipe(formatearTiempos).done(function (html) {
    fav_bus += html;
});

The fav_bus after the change (in the function) it's okay but console.log(fav_bus) just after the function and it's wrong. It's like it didn't changed within the function.

I've tried to return the html but what it ouputs is [Object, object] (as string).

Any hints?

EDIT:

I've tried to store it into a temporal DOM element and it's ok but I'm not being able to output that HTML (although it's there).

pedirTiempos(numero).pipe(formatearTiempos).done(function(html){
        fav_bus += html + '</ul></div>';
        $('#busTemp').html(fav_bus);
});

if ($('#busTemp').length > 0){
   console.log($('#busTemp').html());

And outputs nothing!


回答1:


From what I can see from your code, done looks like an asynchronous call. So the function you are passing to it is most likely getting run after fav_bus += '</ul></div>. This is why you don't see the change.

If you put a console.log inside the function you pass to done and another console.log just after the call to done, you'll probably see the outside console.log run first.

To fix this problem, any subsequent operations with fav_bus need to be done inside the anonymous function that you are passing to done.

Also, you cannot really return anything from an asynchronous function. This is why you need a callback, which will operate on the asynchronous result.

EDIT

Changing the code to for..in shouldn't really break anything unless you're explicitly using the loop index for something. You should be able to get it to work as-is with the following change:

if (tipo == 'bus') {
    favoritos = true;
    fav_bus = '<div data-role="collapsible>' + '<h3>Parada ' + numero + '</h3>' + '<ul data-role="listview" data-inset="true" id="' + itemKey + '">';
    pedirTiempos(numero).pipe(formatearTiempos).done(function (html) {
        fav_bus += html + '</ul></div>';

        // Ya tenemos los datos formateados
        if (fav_bus != '') {
            $('#contentFavoritos').append('<h3 style="text-align: center;">Paradas de Bus</h3>' + '<div data-role="collapsible-set">' + fav_bus + '</div>');
        }
    });
}



回答2:


The fav_bus variable is local to the .live function and not visible to .done.

Moving the code out of the anonymous functions, this would be the same as:

function foo() {
   var a = 5;
   bar();
}

function bar() { // "a" is out of scope here.
   a += 5;
}


来源:https://stackoverflow.com/questions/8359028/why-the-variable-is-out-of-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!