Search code examples
javascriptobjectnestedtabulator

Accessing Javascript nested functions and objects


I am using Tabulator data grid javascript library, it initiates like this:

let grid = new Tabulator("#grid1", {// configuration goes here});

As any other Javascript library, Tabulator allows to use various methods like so: grid.setData().

In my project there are tens of grids and I want to organize them better in my Javascript files. I am trying to create a single function/object and put all grid objects inside, then access function/object members to initiate required grid and still be able to access Tabulator methods like grid.setData().

Example:

function allGrids() {
    this.grid1 = new Tabulator("#grid1");
    this.grid2 = new Tabulator("#grid2");
    this.grid3 = new Tabulator("#grid1");

    let gridsObj = {
      grid1: this.grid1,
      grid2: this.grid2,
      grid3: this.grid3
    };

    return gridsObj;
}

let grids = new allGrids();

// Access grid1
grids.grid1
// Access grid2
grids.grid2
// Access grid3
grids.grid3

I expect it to work like so: grids.grid1, also other Tabulator methods should be accessible to reload/update data like so: grids.grid1.setData().

After placing multiple Tabulator objects inside allGrids function, all three grids are initiated at the same time. How to stop them all automatically executing and make it work only when specific object member is called?

What am I doing wrong? Thank you!


Solution

  • function allGrids() {
        this.grid1 = () => new Tabulator("#grid1");
        this.grid2 = () => new Tabulator("#grid2");
        this.grid3 = () => new Tabulator("#grid1");
    
        let gridsObj = {
          grid1: this.grid1,
          grid2: this.grid2,
          grid3: this.grid3
        };
    
        return gridsObj;
    }
    
    let grids = new allGrids();
    
    // Access grid1
    grids.grid1()
    // Access grid2
    grids.grid2()
    // Access grid3
    grids.grid3()