Setting switch state inside onInit causes onInit to fire again for that element
I have to initialize some switches in my page depending on some external state. That state can be null, true or false:
$('.switch-checkboxes').bootstrapSwitch({
indeterminate: true,
onInit: function(e) {
var state = false // or true or null
if (state == true) {
$(this).bootstrapSwitch('state', true, true);
} else if (state == false) {
$(this).bootstrapSwitch('state', false, true);
}
}
});
However, when that onInit fires and the state is either true or false, onInit fires again for that element, causing $(this).bootstrapSwitch('state', false, true); to run again and then entering on an infinite loop.
I have the same problem! Is there any workaround already?
I don't remember how I ended up fixing this. 🤔
What I remember is that we were using AngularJS on that project, which then used this plugin. I'm not sure now if they ended up reimplementing this entire lib or ended up fixing this bug.
I'm not using Angular but thank you anyway. I've just ended up using the global script variable which is set to true right after the first onInit event so within the next loop iteration I know it was previously inited and I exit it.