Javascript-форум (https://javascript.ru/forum/)
-   Javascript под браузер (https://javascript.ru/forum/css-html/)
-   -   объект и setInterval (https://javascript.ru/forum/css-html/26579-obekt-i-setinterval.html)

posta 13.03.2012 20:47

объект и setInterval
 
Ребята, подскажите как правильно оформить функцию. Чувствую что неправильно написано. хотя работает.

var poller = {
	url:		'get.php',
	time:	5000,
	cmd:	'polling',
	isStarted:	false,

	start: function () {
		this.isStarted=true;
	
		setInterval(function() {poller.get({ "cmd" : poller.cmd },clb);}, this.time);
		function clb(res){console.log(res);}		
	
	},

	get: function (d, callback,ajerror) {
		if(!callback) callback = $.noop;
		if(!ajerror) ajerror = $.noop;

		$.ajax({type: 'GET',url: this.url,
			data : d,
			success : callback,
			error:  ajerror
		});
	}
}


Вместо poller.get и poller.cmd - там хотелось бы иметь this.get и this.cmd соответственно.
Включается poller.start();

и почему не работает вариант следующий:

setInterval(this.get({ "cmd" : this.cmd },clb), this.time);

Или я чего то не понимаю?

Rootpassword 13.03.2012 20:58

this при setInterval это window

posta 13.03.2012 21:09

в setInterval - да. в Callback - это ajax.

Но почему тогда this.time - тогда работает? ведь это же setInterval

nikita.mmf 13.03.2012 22:02

в jquery усть функция прокси
setInterval( $.proxy(this.get({ "cmd" : this.cmd },clb), this), this.time)

в ajax есть параметр context
$.ajax({type: 'GET',url: this.url,
            data : d,
            success : callback,
            error:  ajerror,
            context: this
        });


Часовой пояс GMT +3, время: 14:55.