Skip to content

Instantly share code, notes, and snippets.

@jasonmit
Created March 13, 2019 20:20
Show Gist options
  • Save jasonmit/13bb7641310bf8217d1e5f8be22081e6 to your computer and use it in GitHub Desktop.
Save jasonmit/13bb7641310bf8217d1e5f8be22081e6 to your computer and use it in GitHub Desktop.
Persisting query params
import { run } from '@ember/runloop';
import { action } from '@ember-decorators/object';
import storageFor from 'os-workflows/utils/storage-for-decorator';
const { assign } = Object;
export function withQueryParamMemory(Klass) {
return class WithQueryParams extends Klass {
@storageFor('route-memory')
_memory;
// NOTE: paramsFor is re-implemented to provide the model hooks with the appropriate
// dynamic segments and query parameters (mimicking the default behavior)
paramsFor(routeName) {
const params = super.paramsFor(...arguments);
const restoredQueryParams = this._findStoredQueryParams(
routeName,
this._router._routerMicrolib.activeTransition
);
const mergedParams = {
...params,
...restoredQueryParams
};
return mergedParams;
}
setupController(controller, model, transition) {
super.setupController(...arguments);
const restoredQueryParams = this._findStoredQueryParams(
this.routeName,
transition
);
run.schedule('afterRender', () => {
controller.setProperties(restoredQueryParams);
// Since we are deferring setting the query parameters (primarily so that they appear in the URL)
// we much notify the controller once it's ready. Logic that was previously done
// inside of the setupController hook will need to be moved into some listener for this
// event name.
controller.trigger('readyState');
});
}
_findStoredQueryParams(routeName /*, transition */) {
// TODO: any qps in the transition object should cause the
// restoration to bail out (return `null`)
const manifest = this._memory.get('queryParams');
if (routeName in manifest) {
return manifest[routeName];
}
return null;
}
@action
queryParamsDidChange(changed, preset, removed) {
const { controller, routeName } = this;
this._memory.set('queryParams', {
...this._memory.get('queryParams'),
[this.routeName]: { ...preset }
});
this._recordQps(preset);
this._scheduleParachuteChangeEvent(
routeName,
controller,
assign({}, changed, removed)
);
return this._super(...arguments);
}
_recordQps(queryParams) {
this._memory.set('queryParams', {
...this._memory.get('queryParams'),
[this.routeName]: { ...queryParams }
});
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment