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

狂风中的少年 提交于 2019-12-13 12:02:11

问题


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();

回答1:


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

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




回答2:


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




回答3:


The value this would otherwise point to (that is, the element the handler is attached to) is also passed in the currentTarget property of the event object. So, if you use the binding function you talked about:

Car.prototype.drive = function(e) {
    // this will be your car object
    // e.currentTarget will be the element that you attached the click handler to
}



回答4:


ok here you are :

var car = {km:0};
$("#sprint").click(function(){
    car.km += 10;
    $(this).css({ left: car.km });
});

I have not tested it but should be straight forward or as for where you went wrong is on your "this" which is looking at the "sprint" element not the "car" object.



来源:https://stackoverflow.com/questions/2864378/jquery-this-binding-issue-on-event-handler-equivalent-of-bindaseventlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!