I just noticed that
widget-synced is triggered twice when you’re trying to edit a widget, click on a text field, write something, triggers
widget-synced once and after that, if you click anywhere else it triggers a second time.
Is this default behavior and can it be prevented in a custom widget?
The reason for this is that the widget will run its update logic on
keydown and also on
change for a given
input element. See https://github.com/WordPress/wordpress-develop/blob/4.7.2/src/wp-admin/js/customize-widgets.js#L891-L907
There are some tradeoffs made when widgets were added to the customizer to bring these PHP-driven interfaces into a JS-driven context. It wasn’t perfect and so this is part of the reason behind the JS Widgets feature plugin, to modernize how custom widgets are implemented in the customizer.
If you want to really just listen for when a widget actually changes its state, you can listen for the control’s underlying
setting change instead. The setting will only be updated once after a given
keydown and subsequent
I kinda managed to fix it, don’t know if it’s the proper way, this is in case of sortable fields, using the stop event and checking if the “Apply” button is inside the widget: https://jsfiddle.net/6h5t5r6y