65 lines
1.7 KiB
JavaScript
65 lines
1.7 KiB
JavaScript
import clone from 'lodash.clonedeep';
|
|
|
|
export default class Router {
|
|
constructor(comp, initialState) {
|
|
this.component = comp;
|
|
this.state = clone(initialState) || {};
|
|
|
|
|
|
window.onpopstate = (event) => {
|
|
const state = event.state;
|
|
if (state) {
|
|
if (state.toDispatch) {
|
|
this.component.dispatch(state.toDispatch);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
update (state) {
|
|
const params = [];
|
|
if (state.params) {
|
|
|
|
let cloned = clone(state);
|
|
|
|
if (cloned.params.rooms != null) {
|
|
this.state.rooms[cloned.params.rooms] = !this.state.rooms[cloned.params.rooms];
|
|
}
|
|
|
|
if (cloned.params.category != null) {
|
|
this.state.category[cloned.params.category] = !this.state.category[cloned.params.category];
|
|
}
|
|
|
|
delete cloned.params['rooms'];
|
|
delete cloned.params['category'];
|
|
|
|
this.state = Object.assign(this.state, cloned.params);
|
|
|
|
const {listingId, bounds, sort, rooms = {}, category = {}, zoom} = this.state;
|
|
|
|
if (listingId) {
|
|
params.push(`listingId=${listingId}`);
|
|
}
|
|
|
|
params.push(`sort=${sort}`);
|
|
params.push(`bounds=${bounds}`);
|
|
params.push(`zoom=${zoom}`);
|
|
params.push(`rooms=${Object.keys(rooms).filter(v => rooms[v]).join(",")}`);
|
|
params.push(`category=${Object.keys(category).filter(v => category[v]).join(",")}`);
|
|
}
|
|
|
|
if (state.toDispatch) {
|
|
window.history.pushState(state, '', `/?${params.join("&")}`);
|
|
} else {
|
|
const oldState = window.history.state;
|
|
if (oldState) {
|
|
const newState = Object.assign(oldState, state);
|
|
window.history.replaceState(newState, '',`/?${params.join("&")}`);
|
|
} else {
|
|
|
|
window.history.replaceState(state, '',`/?${params.join("&")}`);
|
|
}
|
|
}
|
|
}
|
|
}
|