Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery "this" binding issue on event handler (equivalent of bindAsEventListener in prototype)

In jquery an event hadler's binding is the event generating DOM element (this points to the dom element). In prototype to change the binding of an event handler one can use the bindAsEventListener function; How can I access both the instance and the DOM element from a event handler?
Similar to How can I bind an event handler to an instance in JQuery?

function Car(){
    this.km = 0;
    $("#sprint").click(this.drive); //setup event handler
}

// event handler
// in it I need to access both the clicked element
// and the binding object (instance of car)
Car.prototype.drive = function(){
    this.km += 10; // i'd like to access the binding (but jq changes it)
    this.css({ // also the element
        left: this.km 
    }); 
    // NOTE that is inside this function I want to access them not elsewhere
}

var car = new Car();
like image 345
clyfe Avatar asked May 19 '10 09:05

clyfe


2 Answers

Hmm, maybe you can use jQuery.proxy()?

http://api.jquery.com/jQuery.proxy/

like image 192
acidtv Avatar answered Oct 17 '22 01:10

acidtv


Just bind a variable to this and use that.

function Car(){
    this.km = 0;
    var that = this;
    $("#sprint").click(function(){
         that.drive(this);
    });
}


Car.prototype.drive = function(element){
    this.km += 10; // i'd like to access the binding (but jq changes it)
    this.css({ // also the element
        left: this.km 
    }); 
    alert(element.innerHTML);
    // NOTE that is inside this function I want to access them not elsewhere
}

The handler passes the element to the instance

like image 31
Sean Kinsey Avatar answered Oct 17 '22 02:10

Sean Kinsey