Pressing a button fires event endlessly


#1

this is my button script

var Button = pc.createScript('button');

Button.attributes.add('shift', {type: 'number'});

var self;
var jumpBy;
// initialize code called once per entity
Button.prototype.initialize = function() {
    self = this;
    
    jumpBy = self.shift;
    
};



// update code called every frame
Button.prototype.update = function(dt) {
    self.entity.button.on('click', this.onRelease, this); 
};

Button.prototype.onRelease = function () {
    self.app.fire('game:Next', jumpBy);
};

and this is what the button activates

var ChangeMaterial2 = pc.createScript('changeMaterial2');
var _app;
var _myID;
var _Material;    


var URL_prefix ='https://s3-us-west-2.amazonaws.com/ticomsoft-image-repo/';
var URL_sufix = '.png';

// exposed fields
ChangeMaterial2.attributes.add("targetMaterial", {type: 'number'}); //targetMaterial
ChangeMaterial2.attributes.add("ID", {type: 'number'}); //ID


var imageUrl;
var material;

ChangeMaterial2.prototype.initialize = function() {
    
    var self = this;
    _Material = self.targetMaterial;
    _myID = self.ID;
    _app=self.app;
    
    material = self.entity.model.meshInstances[_Material].material;    
    UpdateID(); //first image is set
  _app.on('game:Next',this.NextImage, this);

};

ChangeMaterial2.prototype.NextImage = function (jump)
{
        
        _myID+=jump;
        this.UpdateID();
        console.log(jump);
        return;
};

ChangeMaterial2.prototype.ImgFromURLwithCORS = function()
    {
        // allow cross origin texture requests
        _app.loader.getHandler("texture").crossOrigin = "anonymous";

        var asset = new pc.Asset("myTexture", "texture", {
            url: imageUrl
        });

        _app.assets.add(asset);
        asset.on("load", function (asset) {
            material.diffuseMap = asset.resource;
            material.update();
        });

        _app.assets.load(asset);
    };

ChangeMaterial2.prototype.UpdateID = function()
{
        imageUrl = URL_prefix+_myID+URL_sufix;
        this.ImgFromURLwithCORS();
};

what should happen is that at on start, first image is set,
and when closing the button it will jump to another image.
the button jump is set to 1.

what happened is that it endlessly switched images every frame as if it was on update, even though it meant to be on event.

what happened?
does the fact that the Fire command is in update makes the fire happen constantly?
i thought its only the button listener is every frame


#2

edit

after i moved the function to Initialize it only happens once

however the question why still remained


#3

Every frame, you were creating a new callback to the click event in the button.

So if 200 frames have passed, you have 200 callbacks. Therefore when the click event was fired, it would call the function 200 times.


#4

now i understand
i was lonking at it the wrong way

thanks