-1

I am working with a library which implement a class Graph that have a method Graph.registerNode()

The methode has the following signature.

Graph.registerNode('node-name', {
  object: {
    options: {
      key: "value"
    },
  updateOption: () => {
   this.options = { key: "other value" }
  }
})

Is it possible to update the options key from updateOptions without using the this keyword?

eakl
  • 501
  • 8
  • 22
  • 1
    Do you understand that executing `updateOption` won't change the value of `object.options.key` - so, you need code that does what you want in the first place before wondering if there's a different way to do it – Jaromanda X Oct 10 '22 at 02:19
  • [Not even your current code that uses `this` does work](https://stackoverflow.com/q/31095710/1048572) – Bergi Oct 10 '22 at 02:33
  • Indeed, the library uses traditional function signature. So I guess, using this keyword is the only way to reference the object from its method? – eakl Oct 11 '22 at 08:48

2 Answers2

0
const options = {
    key: "value"
};

Graph.registerNode('node-name', {
    object: {
        options,
    }
    updateOption: () => {
        options.key = "other value";
    }
})

How about this?

tom10271
  • 4,222
  • 5
  • 33
  • 62
  • That was my first thought. But once the `registerNode` method is called, and the node is registered, any call of updateOptions method will not update the `{ object: { options } }`. I think both object and updateOption are handled internally at the same time by the registerNode method. – eakl Oct 10 '22 at 02:24
0

I was able to solve this via a factory function

const factoryFunction = () => {
  let options: {
    key: "value"
  }
  
  return Object.freeze({
    updateOption: () => {
      options = {
        key: 'updated value',
      }
    },
    printOption: () => {
      console.log(options)
    }
  })
}

const config = factoryFunction()

Graph.registerNode('node-name', config)

eakl
  • 501
  • 8
  • 22