Multiple mag callbacks issue

Posted on
  • Hi @Gordon,

    Suppose you have

    var zero=Puck.mag();
    
    function onMag(m) {
     m.x -= zero.x;
      m.y -= zero.y;
      m.z -= zero.z;
      var v=Math.sqrt(m.x*m.x+m.y*m.y+m.z*m.z).toF­ixed(0);
     console.log(v);
    }
    
    function main() {
         Puck.on('mag', onMag);
         Puck.magOn();
    }
    

    Multiple calls to main() will result multiple calls to onMag() function, which once the mag is stopped (Puck.magOff()) all are stopped and started if the mag is on (Puck.magOn()). Is there something like an id of the previous callback in order to be stopped ?

    Calling main() 10 times you will have v like that:

    21
    1167
    2355
    3543
    4731
    5919
    7107
    8295
    9484
    10672

    i.e. mag values are exploding even without magnet close to the Puck.

    I came upon this issue because in general I have:

    function myMain() {
         Puck.on('mag', onMag);
         Puck.magOn();
    }
    
    E.on('init', function() {
      myMain();
    });
    
    myMain();
    

    which once the code is uploaded everything is working fine, but when saved I have two callbacks on the mag, if you save it again you will have three callbacks on the mag, etc. How can I have a single function where to receive the current mag values ?

    Thank you!

  • If you have the function handy you can do Puck.removeListener('mag', onMag) : http://www.espruino.com/Reference#l_Obje­ct_removeListener

    Note that if you do:

    function main() {
      function onMag(m) {
       m.x -= zero.x;
        m.y -= zero.y;
        m.z -= zero.z;
        var v=Math.sqrt(m.x*m.x+m.y*m.y+m.z*m.z).toF­ixed(0);
       console.log(v);
      }
       Puck.removeListener('mag', onMag);
       Puck.on('mag', onMag);
       Puck.magOn();
    }
    

    It won't work though, because onMag is basically a different function each time.

    Or you can just do Puck.removeAllListeners('mag'): http://www.espruino.com/Reference#l_Obje­ct_removeAllListeners

    But personally if you can I'd just make sure you only call Puck.on('mag', once - there's no need to call it at startup each time because Espruino will remember.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Multiple mag callbacks issue

Posted by Avatar for user73560 @user73560

Actions