• Yes, my personal recommendation.

    The onInit() function is (one of) the entry point(s) into the application as the 'last' step of power-up and initialization of Espruino. I prefer onInit(){} over E.on("init",function(){...}) because I can better control eventual init sequence when putting things together (rather than using the thing's individual E.on("init",...). Take a look at Saving code on Espruino.

    @Gordon made lots of strides to make things easy and worry free, but some is outside of control of Espruino system, because a module can do what it wants when connecting. Some modules get some states/values initialized which save on save(), but are not valid anymore when restored, because the states/values depend (also) on external systems, such as session/connection/socket IDs.

    When designing the structure of my code, I separate the runtime/variable dependent things from the static/fixed things... and always run the runtime dependent things in the onInit(). This goes even as far as pinMode(), setInterval()s, setTimeout()s, etc., even though they can be saved and restored. With that I make sure that what ever happened to get to a particular state, is re-doable at the later power-cycle. Important is to save the code - after development concluded - before executing onInit() or a-like - manually (or by timeout, as described in next paragraph).

    Also - to simplify development (not to have to enter after every upload onInit() - I put a last line in reading

    setTimeout(onInit,500); // remove this line before 'final' upload for  save()
    

    (@Gordon, I'm sure this line could be made conditional on some Espruino system info which indicates 'load an start of code' by a plain power up vs an upload on a connected and running Espruino. Which such distinction, the line would not have to be removed before final upload for save().)

    @Hapseleg, structuring code in your particular case would extract the (nested) anonymous functions into named functions (or methods of an object). This results in a flatter hierarchy - less levels - and allows to give names to 'things' and foster reuse. You already do it for storing 'configuration things', such as WIFI NAME and OPTIONS, as 'variabe' values. Same you can to for functions, such as for the function in ws.on("open",function(){...}), as well as within its (nested) functions. It is helpful when application code grows in size and complexity.

  • Thank you so much for the very thorough explanation and the great tips. People such as you are those who make communities great :)

About

Avatar for allObjects @allObjects started