Fix: product-sorter - scope-selector readiness detection #1375
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Random crash on Catalog >> Category page in admin.
The issue is much easier to replicate when you enable xDebug. Overall the problem is caused by a race-condition of different ui-components, which means that it's occurring randomly and might take some time to repeat.
Pre-requisites
Steps
Expected
Actual
Symptoms
The sorted_products initiates sometimes (because require.js is async and initiates components somewhat randomly when they're on same level) before the ui.checkbox for use_store_positions which means that switchScope triggers when it's default value is being set.
This is not intended behaviour and the product sorting control actually switch to disabled state even when in store_id=0 scope.
Discussion
Luckily for us, the ui-components listens VS imports has been built so that the processing of imports mapping triggers after value change listens (I presume that the previous code in this specific JS file already was trying to fix the same issue that this PR is re-visiting); This means that while the initial value is being set (when the components that we're listening) is not yet fully initiated, the import target is not even properly set yet.
Therefore the scopeSwitcher (import target) is not yet set (undefined), and will be set AFTER the source element has properly initiated.
Solution
This could be seen as a core M2 bug as one could argue that listeners should not be notified when the thing they're listening to is not yet properly set up.
But in the context of product-sorter: we can just ignore calls to switchScope until the imported value of scopeSwitcher has actually been imported (which means that it ends up being either 1 or 0, but definitely not undefined).
NOTE: even if we see this as core bug, you'd still want this module to provide a solution that works for all M2 releases.