debian-mirror-gitlab/app/assets/javascripts/ide/sync_router_and_store.js

55 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-06-23 00:09:42 +05:30
/**
* This method adds listeners to the given router and store and syncs their state with eachother
*
* ### Why?
*
* Previously the IDE had a circular dependency between a singleton router and a singleton store.
* This causes some integration testing headaches...
*
* At the time, the most effecient way to break this ciruclar dependency was to:
*
* - Replace the router with a factory function that receives a store reference
* - Have the store write to a certain state that can be watched by the router
*
* Hence... This helper function...
*/
export const syncRouterAndStore = (router, store) => {
const disposables = [];
let currentPath = '';
// sync store to router
disposables.push(
store.watch(
2021-03-08 18:12:59 +05:30
(state) => state.router.fullPath,
(fullPath) => {
2020-06-23 00:09:42 +05:30
if (currentPath === fullPath) {
return;
}
currentPath = fullPath;
router.push(fullPath);
},
),
);
// sync router to store
disposables.push(
2021-03-08 18:12:59 +05:30
router.afterEach((to) => {
2020-06-23 00:09:42 +05:30
if (currentPath === to.fullPath) {
return;
}
currentPath = to.fullPath;
store.dispatch('router/push', currentPath, { root: true });
}),
);
const unsync = () => {
2021-03-08 18:12:59 +05:30
disposables.forEach((fn) => fn());
2020-06-23 00:09:42 +05:30
};
return unsync;
};