I have some data that seems to disappear from a class on a wakeup call. There is an article about making this mistake by holding the class refernce in a local variable & succumbing to the garbage collector. In my code below, you can see it is stored in a permanent global variable.
Console:
2016-07-01 16:22:48 UTC-5 [Status] Device connected 2016-07-01 16:22:48 UTC-5 [Device] magic data <-- First call from runOnStartup 2016-07-01 16:22:49 UTC-5 [Device] ERROR: the index 'data' does not exist <-- Second call 2016-07-01 16:22:49 UTC-5 [Device] ERROR: at getData:9
Code:
`class example1 {
data = “”
constructor(_data) {
data = _data
}
function getData() {
server.log(data)
imp.wakeup(1,this.getData)
}
}
inst1 <- example1(“magic data”)
function runOnStartup() {
inst1.getData()
}
runOnStartup();`
Note: This also fails:
`
…
inst1 <- example1(“magic data”)
inst1.getData()
`
Here is an even more basic example that fails equally:
`
class example1 {
data = “magic data”
constructor() {
}
function getData() {
server.log(data)
imp.wakeup(1,this.getData)
}
}
inst1 <- example1()
inst1.getData()
`
When using a callback, bind your current context to it with bindenv()
ie instead of imp.wakeup(1,this.getData), try imp.wakeup(1,getData.bindenv(this))
Otherwise, getData will be called with a global context and “data” will not be visible.
Another way around it, if you are not referring to anything particular to the class instance, would be this:
`function getData() {
server.log(example1.data)
imp.wakeup(1,example1.getData)
}
`
This could be called in any context
Success!
I thought for sure that bindenv wouldn’t work. After you mentioned it I thought it was a weak reference. It did work & I just found in the docs:
Note In standard Squirrel, bindenv keeps a weak reference to the object, but in Electric Imp Squirrel, it is a strong reference.
(source)
Thank you.