Move addItemToShelf into an event instead of class method

This commit is contained in:
Robbie Antenesse 2020-09-16 16:54:29 -06:00
parent a3a8914413
commit fc643c6388
4 changed files with 38 additions and 37 deletions

View File

@ -20,6 +20,39 @@ export const appListeners = (app, state, emitter) => {
});
});
emitter.on(state.events.ADD_TO_SHELF, async (book, shelfId, callback = () => {}) => {
let bookId;
if(typeof book.source !== 'undefined' && typeof book.uri !== 'undefined') {
const bookSearchResult = await fetch('/api/books/getId', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(book),
}).then(response => response.json());
if (typeof bookSearchResult.error !== 'undefined') {
console.error(bookSearchResult);
return bookSearchResult;
}
bookId = bookSearchResult;
} else {
bookId = book.id;
}
return fetch('/api/shelf/addItem', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
shelfId,
bookId,
}),
}).then(result => callback(result));
});
state.i18n.fetchLocaleUI().then(() => {
app.checkIfLoggedIn(state).then(isLoggedIn => {
emitter.emit(state.events.RENDER); // This should hopefully only run once after the DOM is loaded. It prevents routing issues where 'render' hasn't been defined yet

View File

@ -1,7 +1,8 @@
import { I18n } from "./i18n";
export const appState = (app, state, emitter) => {
state.events.SET_LANGUAGE = 'set-language';
state.events.SET_LANGUAGE = 'setLanguage';
state.events.ADD_TO_SHELF = 'addToShelf';
state.language = app.getSettingsItem('lang') ? app.getSettingsItem('lang') : (navigator.language || navigator.userLanguage).split('-')[0];
state.viewStates = {};

View File

@ -148,11 +148,11 @@ export class SearchController extends ViewController {
}
addToShelf(bookData, shelfId) {
const shelfController = new ShelvesController(this.appState, this.i18n);
shelfController.addItemToShelf(bookData, shelfId).then(result => {
const { ADD_TO_SHELF, RENDER } = this.appState.events;
this.emit(ADD_TO_SHELF, bookData, shelfId, (result) => {
console.log(result);
this.showShelves = false;
this.emit(this.appState.events.RENDER);
this.emit(RENDER);
});
}
}

View File

@ -42,37 +42,4 @@ export class ShelvesController extends ViewController {
this.state.loadedShelves[this.targetShelf] = shelf;
});
}
async addItemToShelf (book, shelfId) {
let bookId;
if (typeof book.source !== 'undefined' && typeof book.uri !== 'undefined') {
const bookSearchResult = await fetch('/api/books/getId', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(book),
}).then(response => response.json());
if (typeof bookSearchResult.error !== 'undefined') {
console.error(bookSearchResult);
return bookSearchResult;
}
bookId = bookSearchResult;
} else {
bookId = book.id;
}
return fetch('/api/shelf/addItem', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
shelfId,
bookId,
}),
})
}
}