How Can I find any Object when I know property value of object

I try create shortcut to icon (html element), which is object and this object has some methods for example. openWindow(), and I want that, when I will click on shortcut,this shortcut run method this object (orginal html element).

Example:

class File{
  constructor(fileName){
  this.name = fileName;
  this.element = document.createElement("div");
  this.addFile();
  }
  
  openWindow(){
    console.log("You opened", this.name);
  }
  
  addFile(){
    document.body.appendChild(this.element);
    this.element.addEventListener('click',openWindow)
  }
}

const orginalElement = new File("file1");

const shortcut = orginalElement.cloneNode(true);
shortcut.addEventListener('click', openWindow);

Maybe I should use WeakMap or something other I don’t know.
So Is any method, which can return object when I know property value of object?
Because in my code each object has ‘id’ property and thoose shortcuts has attribute ‘id’ which should be same as property id of orginal object.

1 thought on “How Can I find any Object when I know property value of object”

  1. If I understand you correctly, you can use arrow functions within your class to make them automatically bound to this, no matter how you use them.

    class FileIcon {
      constructor(fileName) {
        this.name = fileName;
        this.addFile();
      }
    
      openWindow = () => {
        console.log("You opened", this.name);
      }
    
      addFile() {
        this.element = document.createElement("button");
        this.element.innerText = "Button " + this.name;
        document.body.appendChild(this.element);
        this.element.addEventListener('click', this.openWindow);
      }
    }
    
    const a = new FileIcon("foo");
    const b = new FileIcon("bar");
    
    const link = document.createElement("a");
    link.href = "#";
    link.innerText = "Link for foo";
    link.addEventListener("click", a.openWindow);
    document.body.appendChild(link);
    Reply

Leave a Comment