Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable by reference to an event handler in javascript?

I simulated a class in JavaScript; it's code is here:

function myclass()
{
    this.count ;

    this.init = function(){
        $("div.mybtn").click({n:this},function(e){
            e.data.n.count++;
        });
    }

    this.getCount = function(){
        alert(this.count);
    }
}

Then I created an instance of this class and executed it's method init(), but when I click on any div.mybtn element, it did not increment the value of this.count.
It seems the object this was passed to event handler by value not by reference.
How I can pass a variable to an event handler by reference?

like image 902
frogatto Avatar asked Jul 16 '13 05:07

frogatto


2 Answers

You can't increment undefined, you have to start somewhere:

function myclass() {
    this.count=0;   // start counting at zero !!!

    this.init = function(){
        $("div.mybtn").on('click', {n:this},function(e){
            e.data.n.count++;
            e.data.n.getCount();
        });
    }

    this.getCount = function(){
        console.log(this.count);
    }
}

var c = new myclass();

c.init()

DEMONSTRATION

like image 66
adeneo Avatar answered Nov 14 '22 22:11

adeneo


Javascript doesn't have pass-by-reference parameters. For what you want, you should use a closure variable:

this.init = function(){
    var self = this;
    $("div.mybtn").click(function(){
        self.count++;
    });
}
like image 40
Barmar Avatar answered Nov 14 '22 20:11

Barmar