0

I have a class (LiveScript) that is instantiated once, but its render method is called many times. Each object created in the render method must have a unique key that stays the same across all invocations of render:

class Test
    ->
     console.log 'constructor, called only once'

    render: ->
        test = {key: 4124312}
        test1 = {key: 234897}
        test2 = {key: 87234}

This works, but instead of hardcoding the key I'd rather generate it. Using a random number will not work since that will generate a new key on each invocation of render. Having some list of keys outside this class and popping items of them won't work either because the order of the created objects in render could change. Any idea if and how I could generate the keys?

Berco Beute
  • 1,115
  • 15
  • 30
  • have you tried generating the key with random number in constructor? – maioman Sep 28 '16 at 16:35
  • This looks like a good case for using [`Symbol`s](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) - especially since you don't seem to care about the identifier value – Rob M. Sep 28 '16 at 16:36
  • why not generate the number in the ctor? – Ven Jan 11 '17 at 09:48

1 Answers1

0

Generating them is one thing - it sounds like you need a way to persist the unique objects with a key that doesn't change during your execution context. This is called persistence.

In JS, you can use an object literal to store your objects, where the key of each entry in your storage object is the unique key of your stored objects:

{
    1234: { name: "test", key: 1234 },
    2345: { name: "test1", key: 2345 },
    3456: { name: "test2", key: 3456 }
}
Danny Bullis
  • 3,043
  • 2
  • 29
  • 35