user622505
user622505

Reputation: 773

SetInterval on functions of an object from within the object

I'm trying to create an object that will work on a <div> by replacing it's inner HTML periodically. I'm stumped with the part 'periodically', though. This is what I'm trying to do (the relevant parts of the code, I'm omitting unrelevant declarations etc.):

function LedDisplay() {
    this.initialize() {
        window.setInterval(this.redraw, 200);
    };

    this.redraw = function() {
        this.shiftDisplayMatrix();
        $('#' + this.name).html(this.createSvg());
    };

    this.shiftDisplayMatrix = function() {
        var firstRow = this.displayMatrix[0];
        this.displayMatrix.splice(0, 1);
        this.displayMatrix.push(firstRow);
    };
};

This results in the following - this.shiftDisplayMatrix is not a function. I believe this is because redraw is called in the global context and there's no this.shiftDisplayMatrix there. What I cannot seem to find is how to achieve what I want.

Or perhaps what I'm trying to do is an antipattern?

Upvotes: 0

Views: 25

Answers (1)

David Li
David Li

Reputation: 1290

Yea, since the context that called this.shiftDisplayMatrix is no longer the object itself, it no longer has access to the function. What you can try doing is

function LedDisplay() {
    var self = this;
    ....
}

and then call self.shiftDisplayMatrix, where we use self to save the context of the LedDisplay object.

Upvotes: 1

Related Questions