문제

아래 코드를 사용하여 코드를 작성하여 지정된 간격으로 웹 메소드를 쿼리합니다.

이제 this.poll 함수에서 나는해야한다

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

대신에

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

즉, Settimeout 이후이 포인터를 느슨하게하기 때문입니다
그래서 나는 수업을 통과해야한다. 인스턴스 이름 :

    var objPoll = new cPoll("objPoll");


인스턴스 이름을 매개 변수로 전달하지 않고 어떻게 얻을 수 있습니까?
나는 거기에서 그것을 가고 싶다!

<!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>
도움이 되었습니까?

해결책 7

또 다른 질문을했습니다. 답은 여기에 있습니다.

JavaScript : IE에 글로벌 변수를 나열합니다

글로벌 변수를 반복하고 "this"에 동등한 지 확인합니다.

다른 팁

괄호를 풀어냅니다 this.Poll(). 시간 간격 후에이 기능을 즉시 호출합니다. 괄호를 풀면 괄호가 발생하지 않고 기능을 전달합니다. setInterval 그리고 당신은 아무런 문제가 없습니다.

setTimeout(this.Poll, this.Interval);

그렇지 않으면 즉시 기능을 호출하고 아무것도 보유하지 않습니다. this 더 이상 포인터, 즉 그냥 삭제합니다.

고정 변형에서 this.Poll 포인터를 잡을 것입니다 this 그리고 삭제되지 않습니다.

나는 단지 말하고 싶었고,이 자기 트릭은 나를 머리카락을 잡아 당기.

나는 이와 같은 참조를 만들려고 생각하지 않았다. ON CLICK 이벤트와 함께 동적으로 만들어진 요소가 내 클래스의 올바른 인스턴스를 호출 할 수 있음을 의미합니다.

당신은 또한 사용할 수 있습니다 :

var name = findInstanceOf(cPoll);

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

에서 http://www.liam-galvin.co.uk/2010/11/24/javaScript-find-instance-of-an-an-object/#read

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

나는 오늘 비슷한 질문에 대한 답변을 제공하여 처음부터 투표 수업을 만들었습니다. 직접 입양하고 싶을 수도 있습니다. 복제하지 않기 위해 다음은 다음과 같은 질문에 대한 링크가 있습니다.

Ajax 및 Dojo로 서버를 투표하십시오 *

* 제목에도 불구하고 내 솔루션은 "바닐라"와 도조 스타일을 모두 제공합니다.

이 편리한 작은 래퍼를 사용하여 주어진 간격 (기본적으로 1 초)에 주기적으로 함수를 실행할 수 있습니다.

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

함수는 false를 반환 할 때까지 반복됩니다.

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

함수가 메소드 인 경우 표시된대로 폐쇄를 만드십시오.

// inside your object
var me = this;
tick(function() {
   return me.doStuff();
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top