Event listener for toggle is 'too fast'

I want to listen for changes on toggles (in the future also on different elements like range-sliders, …) and then send the new boolean state over a socket. I’ve encountered the problem that the “old” state is transmitted, before the animation ends.

Small code fragment:

--- JS ---

$('.customClass').on('touchend mouseup keydown', function (e) {
  // If changed element is a toggle
  if ((e.srcElement.className).includes('toggle')) {
    // e.srcElement = span.toggle-icon, so we have to use the parent for app methods
    var toggle = app.toggle.get(e.srcElement.parentElement);
    // Send new state: toggle.checked

--- HTML ---

<label class="toggle toggle-init customClass" data-id="someID">
  <input type="checkbox" />
  <span class="toggle-icon"></span>

Explanation: The socket provides an array with many states about lamps (on/off, brightness), doors (opened/closed), etc. that is editable from multiple clients. So if Client A changes something, the new state will be pushed to Client B. If a Client changes a toggle, the new state should be transmitted. However, this should only happen on touchend mouseup keydown because toggle:change results in a loop (Client A changes toggle and sends new state ==> Client B updates new state according to Client A ==> This update will fire toggle:change again on Client B ==> Client B sends new state ==> and so on…).
My problem is: if I click on a toggle, the current/old state is sent and after that the toggle changes its position. If toggle is false and I click on it, ‘false’ is sent and toggle goes into position ‘true’ and vice versa. Also if I slowly drag the toggle to one side, nothing is detected.

  • This may help =>
    toggle events
  • I think on toggle:change event, if you try to update socket array's state by =>

state: // your updated state
state: // your updated state

  • Alter this.$setState as your *requirements.
  • more on setstate here

Hi, maybe “socket array” was worded wrongly, sorry for that. Changes are done by calling a different function from socket.io.