0

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?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
donald
  • 7
  • 1

1 Answers1

0

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);
}
Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81
  • Hi Matteo, THX for your Answer. "this" is already pointing at the divElement. this.id returns the correct id. Therefore this.divElement doesn't work either... unfortunately. – donald Oct 31 '13 at 10:35
  • Cool :-) You saved me much time and getting frustrated. Do you have any explanation for having to this in such a strange way? – donald Oct 31 '13 at 10:59
  • It is not strange, please read my answer again: `if you created a new jQuery object, it will only have its default properties set by the jQuery library.`, but I think this should work if you changed the `paperClass` function: `console.log($(this)[0].paperElement);` – Matteo Tassinari Oct 31 '13 at 11:18