Select parent object from a field in js

I am relatively new to OOP so I am not sure about the terminology.

I have created a DOM element as a field of an object (eg myObject.myElement) and I appended the element to the document. The object has a .mousemove() event attached (using jQuery). I want to be able to select the object (myObject) for whom the selected element (myElement) is a field so that I can access other fields of the object. There is more than one object and the event handler is the same for elements of different objects. Is it possible to select the parent object of the element? Do I need to give the element the same fields so that I can access the same data?

I want to be able to do something like this but maybe it is not that straightforward:

$('.bubble').on({mousemove: function () {
    parentObject = this.parentObject();
    alert(parentObject.otherDataField);
});

The element was created like this:

function bubbleObject(value)
{
    this.value = value;
    this.element = document.createElement('div');
    $(this.element).appendTo('.bubbles');
}

myFirstBubble = new bubbleObject(10);
mySecondBubble = new bubbleObject(100);

and I need to be able to access the value field for the object (I am making it simpler as the code is pretty long and mostly irrelevant to my issue).

Do I need to do this:

function bubbleObject(value)
{
    this.value = value;
    this.element = document.createElement('div');
    $(this.element).appendTo('.bubbles');
    this.element.value = value; // add same value to element
}

or is there a better way?

Answers


A back reference to the parent could be better than copying values:

function bubbleObject(value)
{
    this.value = value;
    this.element = document.createElement('div');
    $(this.element).appendTo('.bubbles');
    this.element.parent = this;
}

However, using this way you have to use element.parent.value instead.


Another approach (as I mentioned before) is to scan all element-containing objects if they contain a specific element. If you don't have all these objects in an array you have to scan all window components (as I said, this is expensive):

function findElement(element) {
  for (obj in window) {
    if (typeof obj === 'object' && obj.myElement == element) {
      return obj;
    }
  }
  return null;
}

This is just an untested draft. And it would be so much better if you have a list of parent objects which you can use instead of window.

function findElement(element) {
  for (int i = 0, l = objList.length; i < l; i++) {
    if (typeof objList[i] === 'object' && objList[i].myElement == element) {
      return objList[i];
    }
  }
  return null;
}

Need Your Help

How to set nested css classes into CssResources

css gwt

for example i have this html div structure

Images only shows src with CKeditor

php database mysqli ckeditor kcfinder

After days of searching for my answer, i could not find anything that solved my problem.