Remove listener using swap function not working

Hot swapping code looks awesome but I can’t quite get it to work for me.

scriptDoStuff.prototype.initialize = function() {

this.app.on("Something", this.onSomething.bind(this));
};


scriptDoStuff.prototype.swap = function (old) {

    //hot swapping is awesome
    this.app.off("Something",old.onSomething.bind(this));
    this.app.on("Something", this.onSomething.bind(this));
};

scriptDoStuff.prototype.onSomething= function(raycast) {
                       
    console.log("Something #123 ");

};

When load the game and change the onSomething code from #123 to #124 I get:
Something #123
Something #124

It’s running the swap function (which is great!) but I’m not properly removing the old function from the event.

I’ve tried it several ways but with no luck. Any ideas?

Thank you.

Noah

The .bind was causing some weirdness so I used the scope param of the on/off functions:

var SwapTest = pc.createScript('swapTest');

SwapTest.prototype.initialize = function() {
    this.app.on("Something", this.onSomething, this);
};


SwapTest.prototype.update = function(dt) {
    if (this.app.keyboard.wasPressed(pc.KEY_SPACE)) {
        this.app.fire("Something");
    }
};

SwapTest.prototype.swap = function (old) {
    //hot swapping is awesome
    this.app.off("Something", old.onSomething, old);
    this.app.on("Something", this.onSomething, this);
};

SwapTest.prototype.onSomething= function(raycast) {                   
    console.log("Something #121 ");
};

That was the answer. This is a super time saver! I think this example should make it’s way onto the documentation. A lot of other people are having similar issues and did not know about the scope param.

1 Like

Good point, I thought it was mentioned in the manual but just checked now and it doesn’t use the scope param at all :thinking: