1

I need to use the value of a boolean variable to trigger an action, and I will use this in several occasions, then is very important I do in the best way. I already search and found a way to use object.watch, like this:

let test1 = {on: false};
teste1.watch('on', function (prop, oldval, newval) {
    if (teste1.on === true) {
        $('#bot').toggleClass('switch-bck');
    } else {
        $('#bot').toggleClass('switch');
    }
    return newval;
});
interact('#bot2')
    .on('down', function (event) {
        event.currentTarget.classList.toggle('switch');
        event.preventDefault();
        if (teste1.on) {
            teste1.on = false;
        } else {
            teste1.on = true;
        }
        document.getElementById('demo').innerHTML = teste1.on;
    })
    .on('up', function (event) {
        event.currentTarget.classList.toggle('switch');
        event.preventDefault();

        document.getElementById('demo').innerHTML = teste1.on;
    });
document.getElementById('demo').innerHTML = teste1.on;

This almost works. When I change the state of teste1.on the first 2 times works well. But after this take the double of changes of teste1.on for the

$('#bot').toggleClass('switch-bck');

be activated. But I see that teste1.on change correctly because I see its value with

document.getElementById('demo').innerHTML = teste1.on;

If I change return newval to return oldval or even remove it, the change that I want happens perfectly, but the value that I se with

document.getElementById('demo').innerHTML = teste1.on;

remain freeze or show "undefined".

Any help? Or even a way to do this without using .watch?

Elzo Valugi
  • 24,234
  • 13
  • 88
  • 112
PhBsa
  • 63
  • 1
  • 4
  • Possible duplicate of [Listening for variable changes in JavaScript or jQuery](http://stackoverflow.com/questions/1759987/listening-for-variable-changes-in-javascript-or-jquery) – Rajesh Aug 08 '16 at 10:33
  • [Object.watch](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/watch) has compatibility and performance issues. Check it before using it. – Rajesh Aug 08 '16 at 10:35

0 Answers0