79 lines
2.1 KiB
JavaScript
79 lines
2.1 KiB
JavaScript
class ToggleHash {
|
|
constructor(data, key) {
|
|
this.data = data;
|
|
this.key = key;
|
|
this.data[key] = {};
|
|
}
|
|
|
|
toggle (field) {
|
|
if (!field) {
|
|
return;
|
|
}
|
|
|
|
const val = this.data[this.key][field];
|
|
this.data[this.key][field] = !val;
|
|
}
|
|
}
|
|
|
|
export default class Router {
|
|
constructor(comp, initialState) {
|
|
this.component = comp;
|
|
this.state = initialState || {};
|
|
|
|
this.roomsToggler = new ToggleHash(this.state, 'rooms');
|
|
this.categoryToggler = new ToggleHash(this.state, 'category');
|
|
|
|
window.onpopstate = (event) => {
|
|
const state = event.state;
|
|
console.log('POPING STATE', state);
|
|
if (state) {
|
|
if (state.toDispatch) {
|
|
this.component.dispatch(state.toDispatch);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
update (state) {
|
|
const params = [];
|
|
if (state.params) {
|
|
|
|
this.roomsToggler.toggle(state.params.rooms);
|
|
this.categoryToggler.toggle(state.params.category);
|
|
|
|
delete state.params['rooms'];
|
|
delete state.params['category'];
|
|
|
|
this.state = Object.assign(this.state, state.params);
|
|
|
|
console.log('router state is: ', this.state);
|
|
const {listingId, bounds, sort, rooms = {}, category = {}} = this.state;
|
|
|
|
if (listingId) {
|
|
params.push(`listingId=${listingId}`);
|
|
}
|
|
|
|
params.push(`sort=${sort}`);
|
|
params.push(`bounds=${bounds}`);
|
|
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) {
|
|
console.log('PUSHING STATE', state);
|
|
window.history.pushState(state, '', `/?${params.join("&")}`);
|
|
} else {
|
|
const oldState = window.history.state;
|
|
if (oldState) {
|
|
const newState = Object.assign(oldState, state);
|
|
console.log('REPLACING STATE', newState);
|
|
window.history.replaceState(newState, '',`/?${params.join("&")}`);
|
|
} else {
|
|
|
|
console.log('PUSHING STATE', state);
|
|
window.history.replaceState(state, '',`/?${params.join("&")}`);
|
|
}
|
|
}
|
|
}
|
|
}
|