javascripteventsthiscyclic-reference

Cyclic referencing doesn't seem work in event handler function


I have an object called paperClass (even though I know, classes don't exist in JavaScript). This is containing a reference to a divElement. Now, by hovering the divElement I want to get a reference to the paperClass object. I tried it the following way:

function paperClass(){
    this.divElement = $("#divElementID");
    this.divElement.paperElement = this;
    this.divElement.hover(this.handleHover);
    console.log(this.divElement.attr("id"));    // -> divElementID
    console.log(this.divElement.paperElement);    // -> paperClass Object
}

paperClass.prototype.handleHover = function(event){
    console.log(this.id);    // -> divElementID
    console.log($(this).attr("id"));    // -> divElementID
    console.log(this.paperElement);     // -> undefined (which seems ok to me)
    console.log($(this).paperElement);  // -> undefined (WHY????)
}

I also tried the .attr() and $data() methods. Unfortunately, I didn't succeed. Do you have any ideas?


Solution

  • The line

    console.log($(this).paperElement);  // -> undefined (WHY????)
    

    has the paperElement property undefined because it was only present in the specific jQuery object you bound to this.divElement.

    If you created a new jQuery object, it will only have its default properties set by the jQuery library.

    Try this instead:

    function paperClass(){
        this.divElement = $("#divElementID");
        this.divElement[0].paperElement = this; // change this line
        this.divElement.hover(this.handleHover);
        console.log(this.divElement.attr("id"));
        console.log(this.divElement.paperElement);
    }
    
    paperClass.prototype.handleHover = function(event){
        console.log(this.id);
        console.log(this.paperElement);
    }