0

I am trying to import jquery into my prototyped class which works initially in the constructor.

I lose my scope of jquery in the call to resizeCanvas event. It says the width() and height() function is undefined.

Is there a way I won't lose the jquery variable.

define(['jquery'], function($) {

    function Canvas() {
        this.canvas   = document.getElementById('canvas');
        this.context  = this.canvas.getContext('2d');
        this.rowbuild = $('#rowbuild');
    }

    Canvas.prototype.addResizeListener = function() {
        window.addEventListener('resize', this.resizeCanvas, false);
    };
    Canvas.prototype.resizeCanvas = function() {
        this.canvas.width  = this.rowbuild.width();
        this.canvas.height = this.rowbuild.height();
    };

    return Canvas;
});
Atherion
  • 584
  • 1
  • 5
  • 14
  • I found the problem I need to pass the context of jquery. $(window).on('resize', this.resizeCanvas); – Atherion Jun 03 '14 at 23:27

1 Answers1

2

You need to bind the listener to the correct context object using bind or $.proxy.

window.addEventListener('resize', this.resizeCanvas.bind(this), false);

Besides, why are you using addEventListener if you are already using jQuery?

plalx
  • 42,889
  • 6
  • 74
  • 90