Javascript Instance Variable Syntax (AJAX page refresh)
Posted
by Rosarch
on Stack Overflow
See other posts from Stack Overflow
or by Rosarch
Published on 2010-04-07T17:59:03Z
Indexed on
2010/04/07
18:03 UTC
Read the original article
Hit count: 224
I'm having difficulty with Javascript instance variables. I'm trying to make an easy way to refresh the chat page, looking for new messages. The AJAX call supplies a mid
, or the lowest message id to be returned. This allows the call to only ask for the most recent messages, instead of all of them.
MessageRefresher.prototype._latest_mid;
function MessageRefresher(latest_mid) {
this._latest_mid = latest_mid; // it thinks `this` refers to the MessageRefresher object
}
MessageRefresher.prototype.refresh = function () {
refreshMessages(this._latest_mid); // it thinks `this` refers to the window
this._latest_mid++;
}
function refreshMessages(latest_mid) {
$.getJSON('API/read_messages', { room_id: $.getUrlVar('key'), mid: latest_mid }, function (messages) {
for (var i = 0; i < messages[0].length; i++) {
var newChild = sprintf("<li>%s: %s</li>", messages[1][i], messages[0][i]);
$("#messages").append(newChild);
}
});
var messageRefresher = new MessageRefresher(0);
setInterval(messageRefresher.refresh, 1000);
This results in all the messages being printed out, over and over again.
I know it has other bugs, but the main issue I'm trying to work out right now is the use of the instance variable. Or is there another way I should be going about doing this?
© Stack Overflow or respective owner