I
I
Ivan Pavlenko2015-05-07 21:13:34
JavaScript
Ivan Pavlenko, 2015-05-07 21:13:34

Javascript image.onload - how to find out the object that set the call?

How to find out who created or initiated an event call in JavaScript?
Now more about the task - loading a texture in WebGL. I implemented like this:

Texture.prototype.loadImage = function(url) {
                image = new Image();
                image.owner = this; // смело, но гложет червь сомнения
                image.onload = function() {
                    gl.bindTexture(gl.TEXTURE_2D, this.owner.texture);
                    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
                }
                image.src = url;
            }

Since onload forgets (or I don't know how to find out) who called it, the actions to load the texture lose their meaning, since it is not known where to load it. I solved the problem by binding to the image object a field indicating the class of the creator, but I did it rudely and clumsily, like this:
image.owner = this;
I understand intellectually that it’s incorrect to do this (it’s possible to block something important) and if anyone knows the correct solution, please tell me how to proceed in such cases .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Taratin, 2015-05-07
@MrGobus

Texture.prototype.loadImage = function(url) {
                var image = new Image();
                var self = this;
                image.onload = function() {
                    gl.bindTexture(gl.TEXTURE_2D, self.texture);
                    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
                }
                image.src = url;
            }

S
Sergey Melnikov, 2015-05-08
@mlnkv

Texture.prototype.loadImage = function(url) {
  var image = new Image();
  image.onload = function() {
    gl.bindTexture(gl.TEXTURE_2D, this.texture);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  }.bind(this);
  image.src = url;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question