Javascript setInterval 및`this` 솔루션
this
내 setInterval
핸들러 에서 액세스해야 합니다.
prefs: null,
startup : function()
{
// init prefs
...
this.retrieve_rate();
this.intervalID = setInterval(this.retrieve_rate, this.INTERVAL);
},
retrieve_rate : function()
{
var ajax = null;
ajax = new XMLHttpRequest();
ajax.open('GET', 'http://xyz.com', true);
ajax.onload = function()
{
// access prefs here
}
}
this.prefs에서 ajax.onload
어떻게 액세스 할 수 있습니까?
setInterval 행은 다음과 같아야합니다.
this.intervalID = setInterval(
(function(self) { //Self-executing func which takes 'this' as self
return function() { //Return a function in the context of 'self'
self.retrieve_rate(); //Thing you wanted to run as non-window 'this'
}
})(this),
this.INTERVAL //normal interval, 'this' scope not impacted here.
);
편집 : " onload
" 에도 동일한 원칙이 적용됩니다 . 이 경우 "외부"코드가 거의 수행하지 않는 일반적인 경우 요청을 설정 한 다음 전송합니다. 이 경우 추가 오버 헤드는 위 코드에서와 같이 추가 기능이 필요하지 않습니다. retrieve_rate는 다음과 같이 보일 것입니다.
retrieve_rate : function()
{
var self = this;
var ajax = new XMLHttpRequest();
ajax.open('GET', 'http://xyz.com', true);
ajax.onreadystatechanged= function()
{
if (ajax.readyState == 4 && ajax.status == 200)
{
// prefs available as self.prefs
}
}
ajax.send(null);
}
this.intervalID = setInterval(this.retrieve_rate.bind(this), this.INTERVAL);
의 기본 동작은 setInterval
전역 컨텍스트에 바인딩하는 것입니다. 현재 컨텍스트의 복사본을 저장하여 멤버 함수를 호출 할 수 있습니다. retrieve_rate 내에서 this
변수는 원래 컨텍스트에 올바르게 바인딩됩니다. 코드는 다음과 같습니다.
var self = this;
this.intervalID = setInterval(
function() { self.retrieve_rate(); },
this.INTERVAL);
보너스 팁 : 일반 함수 참조 (멤버 함수가있는 개체 참조와 반대)의 call
경우 JavaScript 또는 apply
메서드를 사용하여 컨텍스트를 변경할 수 있습니다 .
브라우저 지원이 향상됨에 따라 이제는 EcmaScript 6 향상, 화살표 =>
방법 을 사용하여 this
적절하게 보존 할 수 있습니다.
startup : function()
{
// init prefs
...
this.retrieve_rate();
this.intervalID = setInterval( () => this.retrieve_rate(), this.INTERVAL);
},
=> 메서드를 사용 하면 간격에 의해 호출되는 this
시기 retrieve_rate()
가 유지 됩니다 . 펑키 한 자아 나 this
매개 변수 전달이 필요 없습니다.
window.setInterval(function(){console.log(this)}.bind(this), 100)
이것은 자바 스크립트에서 합법적이며 많은 코드를 절약합니다. :)
대부분의 경우 연속 메서드 호출에 대해이 컨텍스트를 실제로 전환하기를 원하기 때문에 이것은 가장 깨끗한 솔루션입니다.
또한 개념을 이해하는 것이 더 쉽습니다.
// store scope reference for our delegating method
var that = this;
setInterval(function() {
// this would be changed here because of method scope,
// but we still have a reference to that
OURMETHODNAME.call(that);
}, 200);
prefs: null,
startup : function()
{
// init prefs
...
this.retrieve_rate();
var context = this;
this.intervalID = setInterval(function()
{
context.retrieve_rate();
}, this.INTERVAL);
},
retrieve_rate : function()
{
var ajax = null;
ajax = new XMLHttpRequest();
ajax.open('GET', 'http://xyz.com', true);
var context = this;
ajax.onload = function()
{
// access prefs using context.
// e.g. context.prefs
}
}
With modern browsers the setInterval method allows additional parameters which are passed through to the function specified by func once the timer expires.
var intervalID = scope.setInterval(func, delay[, param1, param2, ...]);
Hence, a possible solution can be:
this.intervalID = setInterval(function (self) {
self.retrieve_rate();
}, this.INTERVAL, this);
A demo:
var timerId;
document.querySelector('#clickMe').addEventListener('click', function(e) {
timerId = setInterval(function (self) {
self.textContent = self.textContent.slice(0, -1);
if (self.textContent.length == 0) {
clearInterval(timerId);
self.textContent = 'end..';
}
}, 250, this);
})
<button id="clickMe">ClickMe</button>
That's not a beauty solution but it's in common usage:
var self = this;
var ajax = null;
//...
ajax.onload = function() {
self.prefs....;
}
참고URL : https://stackoverflow.com/questions/2749244/javascript-setinterval-and-this-solution
'Nice programing' 카테고리의 다른 글
onclick 전체 화면으로 이동 (0) | 2020.12.02 |
---|---|
Mac OSX에서 Postgres DB가 시작되지 않음 : 오류 메시지 : Unix 도메인 소켓 연결 (0) | 2020.12.02 |
공개 디렉토리를 얻는 방법? (0) | 2020.12.02 |
Gradle을 사용하여 opencv를 사용하는 방법은 무엇입니까? (0) | 2020.12.02 |
App.settings-Angular 방식? (0) | 2020.12.02 |