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?