Question

J'utilise le code suivant pour écrire du code pour interroger un procédé Web dans un intervalle spécifié.
maintenant dans la fonction this.Poll que je dois faire

this.tmo = setTimeout(this.strInstanceName + ".Poll()", this.iInterval);

au lieu de

this.tmo = setTimeout(this.Poll(), this.iInterval);

parce que IE perd le pointeur après ce setTimeout
Je dois donc passer la classe, il est le nom d'instance:

    var objPoll = new cPoll("objPoll");


Comment puis-je obtenir le nom de l'instance sans passer comme paramètre?
Je veux avoir là outta!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Intervall-Test</title>
    <script type="text/javascript" language="javascript">


        function test()
        {
            alert("Test");
            test.tmo = setTimeout(test, 2000);

            test.Clear = function()
            {
                clearTimeout(test.tmo);
            }
        }




        function cPoll(strInstanceName)
        {
            this.strInstanceName = strInstanceName ;
            this.iInterval = 2000;
            this.tmo=null;
            this.cbFunction=null;

            this.Poll = function()
            {
                this.cbFunction();
                this.tmo = setTimeout(this.strInstanceName + ".Poll()", this.iInterval);
            }

            this.Start = function(pCallBackFunction, iIntervalParameter)
            {


                if(this.tmo != null)
                    this.Stop();

                if(iIntervalParameter && iIntervalParameter > 0)
                    this.iInterval=iIntervalParameter;

                this.cbFunction=pCallBackFunction;
                if(this.cbFunction!=null)
                    this.Poll();
                else
                    alert("Invalid or no callback function specified");
            }

            this.Stop = function()
            {
                if(this.tmo != null)
                {
                    clearTimeout(this.tmo);
                    this.tmo=null;
                }
            }
        }


        function CallBackFunction()
        {
            alert("PollCallBack");
        }

        // test();
        // test.Clear();


        var objPoll = new cPoll("objPoll");
    </script>
</head>

<body>
<h1>Test</h1>

<input type="Button" value="Start polling" onclick="objPoll.Start(CallBackFunction,3000);" />
<input type="Button" value="Stop polling" onclick="objPoll.Stop();" />
</body>
</html>
Était-ce utile?

La solution 7

J'ai posé une autre question, la réponse est ici:

JavaScript: Liste des variables globales dans IE

Itère les variables globales et vérifier si elle est égale à « ce ».

Autres conseils

Lâche la parenthèse dans this.Poll(). Vous appelez cette fonction tout de suite, pas après un intervalle de temps. Si vous perdez les supports, il passera une fonction, pas un résultat de celui-ci, à setInterval et vous n'avez des questions.

setTimeout(this.Poll, this.Interval);

Sinon, vous appelez immédiatement la fonction de suite et rien ne tient plus this pointeur et IE effacements juste.

Dans la variante fixe, this.Poll tiendra pointeur vers this et il ne sera pas supprimé.

Je voulais juste dire, ce truc auto m'a sauvé ton de tirer les cheveux.

Je ne pensais pas créer une référence comme celui-ci. Cela signifie des éléments dynamiquement créés avec des événements de clic peuvent appeler l'instance correcte de ma classe.

Vous pouvez également utiliser:

i.e..

var name = findInstanceOf(cPoll);

function findInstanceOf(obj) {
    for (var v in window) {
        try {
            if (window[v] instanceof obj)
                return v;
        } catch(e) { }
    };
    return false;
}

var self = this;
this.tmo = setTimeout(function(){
     self.Poll();
}, this.iInterval);

Vous pouvez utiliser ce petit emballage pratique pour exécuter une fonction périodique à intervalle donné (1 sec par défaut):

function tick(func, interval) {
    return (function() {
        if(func())
            setTimeout(arguments.callee, interval || 1000);
    })();
}

La fonction est répétée jusqu'à ce qu'il retourne false:

tick(function() {
   if(should stop) return false;
   do stuff
   return true;
});

Si la fonction est une méthode, faire une fermeture comme indiqué

// inside your object
var me = this;
tick(function() {
   return me.doStuff();
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top