frogatto
frogatto

Reputation: 29285

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?

Upvotes: 7

Views: 11647

Answers (3)

adeneo
adeneo

Reputation: 318342

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

Upvotes: 4

Barmar
Barmar

Reputation: 782529

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++;
    });
}

Upvotes: 3

mohkhan
mohkhan

Reputation: 12335

You can write a bind function and bind the context with the event handler.

Function.prototype.bind = function(){
    var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();

    return function(){
        fn.apply(object, args.concat(Array.prototype.slice.call(arguments)));
    }
}

function myclass()
{
    this.count ;

    this.clicked = function(){
        this.count++;    
    };

    this.init = function(){
        $("div.mybtn").click(this.clicked.bind(this));
    }

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

Upvotes: 1

Related Questions