Javascript Instance Variable Syntax (AJAX page refresh)
- by Rosarch
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?