Foros del Web » Programando para Internet » Javascript »

Acceder una variable fuera de una funcion?

Estas en el tema de Acceder una variable fuera de una funcion? en el foro de Javascript en Foros del Web. Buenas Tengo esto: Código: <script type="text/javascript"> /* * Copyright 2010 Nicholas C. Zakas. All rights reserved. * BSD Licensed. */ function CrossDomainStorage(origin, path){ this.origin = ...
  #1 (permalink)  
Antiguo 14/06/2012, 03:30
 
Fecha de Ingreso: abril-2012
Mensajes: 39
Antigüedad: 12 años
Puntos: 0
Acceder una variable fuera de una funcion?

Buenas

Tengo esto:


Código:
<script type="text/javascript">

                /*
 * Copyright 2010 Nicholas C. Zakas. All rights reserved.
 * BSD Licensed.
 */
function CrossDomainStorage(origin, path){
    this.origin = origin;
    this.path = path;
    this._iframe = null;
    this._iframeReady = false;
    this._queue = [];
    this._requests = {};
    this._id = 0;
}

CrossDomainStorage.prototype = {

    //restore constructor
    constructor: CrossDomainStorage,

    //public interface methods

    init: function(){

        var that = this;

        if (!this._iframe){
            if (window.postMessage && window.JSON && window.localStorage){
                this._iframe = document.createElement("iframe");
                this._iframe.style.cssText = "position:absolute;width:1px;height:1px;left:-9999px;";
                document.body.appendChild(this._iframe);

                if (window.addEventListener){
                    this._iframe.addEventListener("load", function(){ that._iframeLoaded(); }, false);
                    window.addEventListener("message", function(event){ that._handleMessage(event); }, false);
                } else if (this._iframe.attachEvent){
                    this._iframe.attachEvent("onload", function(){ that._iframeLoaded(); }, false);
                    window.attachEvent("onmessage", function(event){ that._handleMessage(event); });
                }
            } else {
                throw new Error("Unsupported browser.");
            }
        }

        this._iframe.src = this.origin + this.path;

    },

    requestValue: function(key, callback){
        var request = {
                key: key,
                id: ++this._id
            },
            data = {
                request: request,
                callback: callback
            };

        if (this._iframeReady){
            this._sendRequest(data);
        } else {
            this._queue.push(data);
        }   

        if (!this._iframe){
            this.init();
        }
    },

    //private methods

    _sendRequest: function(data){
        this._requests[data.request.id] = data;
        this._iframe.contentWindow.postMessage(JSON.stringify(data.request), this.origin);
    },

    _iframeLoaded: function(){
        this._iframeReady = true;

        if (this._queue.length){
            for (var i=0, len=this._queue.length; i < len; i++){
                this._sendRequest(this._queue[i]);
            }
            this._queue = [];
        }
    },

    _handleMessage: function(event){
        if (event.origin == this.origin){
            var data = JSON.parse(event.data);
            this._requests[data.id].callback(data.key, data.value);
            delete this._requests[data.id];
        }
    }

};


var remoteStorage = new CrossDomainStorage("http://algo.com", "/server.html");
                    remoteStorage.requestValue("unallave", function(key, value){
                    alert("El valor para '" + key + "' es '" + value + "'");

                    });

                    alert ("Quiero accerder value aqui! " + value);
    </script>
Creo que es auto explicatorio y es una pregunta MUY tonta :( y de novato: Quiero acceder value fuera de esa funcion. Haciendo algo como:

Código:
var unavariable="";
var remoteStorage = new CrossDomainStorage("http://algo.com", "/server.html");
                    remoteStorage.requestValue("unallave", function(key, value){
                    alert("El valor para '" + key + "' es '" + value + "'");
                    unavariable=value;
                    });
                   alert ("probamos " + unavariable);
Código:
var unavariable="";
var remoteStorage = new CrossDomainStorage("http://algo.com", "/server.html");
                    unavariable=remoteStorage.requestValue("unallave", function(key, value){
                    alert("El valor para '" + key + "' es '" + value + "'");
                    return value;
                    });
                   alert ("probamos " + unavariable);
Tampoco funciona. Ninguna de las dos. Como puedo lograr lo que quiero? Gracias!
  #2 (permalink)  
Antiguo 14/06/2012, 19:47
Avatar de America|UNK  
Fecha de Ingreso: noviembre-2006
Ubicación: Piura - Perú
Mensajes: 582
Antigüedad: 17 años, 4 meses
Puntos: 56
Respuesta: Acceder una variable fuera de una funcion?

-----------------------
requestValue: function(key, callback){
var request = {
key: key, .....................

this._sendRequest(data);


var unavariable="";
var remoteStorage = new CrossDomainStorage("http://algo.com", "/server.html");
unavariable=remoteStorage.requestValue("unallave", function(key, value){
alert("El valor para '" + key + "' es '" + value + "'");
return value;
});

alert ("probamos " + unavariable);

-----------------------

Fijate que el callback de requestValue está llamando a this._sendRequest(data);
Donde data esta nuestro callback, pero mira la funcion _sendRequest nuestro callback no esta llamandose por ninguna parte.

En pocas palabras tu callback no está realizando ninguna acción por eso no asigna la variable.
__________________
/* El que atiende, entiende..., el que entiende, aprende!.
Desarrollo Web Freelance, Contactar */
  #3 (permalink)  
Antiguo 18/06/2012, 01:49
 
Fecha de Ingreso: abril-2012
Mensajes: 39
Antigüedad: 12 años
Puntos: 0
Respuesta: Acceder una variable fuera de una funcion?

Cita:
Iniciado por America|UNK Ver Mensaje
-----------------------
requestValue: function(key, callback){
var request = {
key: key, .....................

this._sendRequest(data);


var unavariable="";
var remoteStorage = new CrossDomainStorage("http://algo.com", "/server.html");
unavariable=remoteStorage.requestValue("unallave", function(key, value){
alert("El valor para '" + key + "' es '" + value + "'");
return value;
});

alert ("probamos " + unavariable);

-----------------------

Fijate que el callback de requestValue está llamando a this._sendRequest(data);
Donde data esta nuestro callback, pero mira la funcion _sendRequest nuestro callback no esta llamandose por ninguna parte.

En pocas palabras tu callback no está realizando ninguna acción por eso no asigna la variable.
Vale entonces que tengo que hacer para que lo haga?

Tengo esto

Código:
remoteStorage.requestValue("something", function(key, value){
					
				
		
					valor=value;
					remoteStorage.v=value;
					
			
					
						hero<?php echo $_SESSION['countforfor']; ?> =  value;
						document.getElementById("fotop<?php echo $_SESSION['countforfor']; ?>").src=hero<?php echo $_SESSION['countforfor']; ?>;
						document.getElementById("fotog<?php echo $_SESSION['countforfor']; ?>").src=hero<?php echo $_SESSION['countforfor']; ?>;
						alert("value " + value);
					
					
					});
Que solo me funciona si pongo el alert. Sin el alert, value se queda con el mismo valor todo el rato.
  #4 (permalink)  
Antiguo 19/06/2012, 00:50
 
Fecha de Ingreso: abril-2012
Mensajes: 39
Antigüedad: 12 años
Puntos: 0
Respuesta: Acceder una variable fuera de una funcion?

Nadie que puede ayudar?
  #5 (permalink)  
Antiguo 19/06/2012, 19:00
Avatar de America|UNK  
Fecha de Ingreso: noviembre-2006
Ubicación: Piura - Perú
Mensajes: 582
Antigüedad: 17 años, 4 meses
Puntos: 56
Respuesta: Acceder una variable fuera de una funcion?

Puedes darme la web de la documentación del script, y que es lo que hace. El problema me huele a que estás queriendo acceder a una variable que no se define hasta que algo no este cargado.
__________________
/* El que atiende, entiende..., el que entiende, aprende!.
Desarrollo Web Freelance, Contactar */
  #6 (permalink)  
Antiguo 21/06/2012, 00:59
 
Fecha de Ingreso: abril-2012
Mensajes: 39
Antigüedad: 12 años
Puntos: 0
Respuesta: Acceder una variable fuera de una funcion?

Disculpas, podia haber jurado que lo habia puesto.

Estoy intentando esto de aqui:


http://www.nczonline.net/blog/2010/09/07/learning-from-xauth-cross-domain-localstorage/

Muchas gracias porque esto me esta matando y llevo unas cuantas semanas con esto.
  #7 (permalink)  
Antiguo 21/06/2012, 07:43
 
Fecha de Ingreso: abril-2011
Mensajes: 1.342
Antigüedad: 13 años
Puntos: 344
Respuesta: Acceder una variable fuera de una funcion?

Buenas,

Si no estoy entendiendo mal, lo que quieres es hacer un llamado AJAX entre dominios distintos. Suponiendo que la llamada este correctamente, si la llamada es asíncrona (por defecto es así), la variable no tendrá valor hasta que llegue la respuesta y tu intentas acceder a ella en el momento justo después de realizar la llamada.

Es decir, todo lo que quieras hacer con el valor que te llega lo tienes que hacer dentro de la función que le pasas a la llamada requestValue (lo de function(key,value)).

Saludos.
  #8 (permalink)  
Antiguo 22/06/2012, 09:14
 
Fecha de Ingreso: abril-2012
Mensajes: 39
Antigüedad: 12 años
Puntos: 0
Respuesta: Acceder una variable fuera de una funcion?

Cita:
Iniciado por alexg88 Ver Mensaje
Buenas,

Si no estoy entendiendo mal, lo que quieres es hacer un llamado AJAX entre dominios distintos. Suponiendo que la llamada este correctamente, si la llamada es asíncrona (por defecto es así), la variable no tendrá valor hasta que llegue la respuesta y tu intentas acceder a ella en el momento justo después de realizar la llamada.

Es decir, todo lo que quieras hacer con el valor que te llega lo tienes que hacer dentro de la función que le pasas a la llamada requestValue (lo de function(key,value)).

Saludos.
Ya intente esto. Lo unico que ocurre es que me repite todo el rato el mismo valor.

La primera vez a=1 pero leugo cuando esta a y b, a=1 y b=1 aunque b le he metido 3

Etiquetas: fuera, funcion, html, js, poo, variables
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 00:34.