framework/js/lib/utils/app.js

61 lines
1.6 KiB
JavaScript
Raw Normal View History

2015-04-25 20:58:39 +08:00
import ItemList from 'flarum/utils/item-list';
2015-05-18 16:43:16 +08:00
import Alert from 'flarum/components/alert';
2015-05-26 10:13:20 +08:00
import ServerError from 'flarum/utils/server-error';
2015-04-25 20:58:39 +08:00
class App {
constructor() {
this.initializers = new ItemList();
this.cache = {};
2015-05-26 10:13:20 +08:00
this.serverError = null;
2015-04-25 20:58:39 +08:00
}
boot() {
this.initializers.toArray().forEach((initializer) => initializer(this));
}
2015-05-18 12:58:15 +08:00
setTitle(title) {
document.title = (title ? title+' - ' : '')+this.config['forum_title'];
}
2015-05-26 10:13:20 +08:00
request(options) {
var extract = options.extract;
options.extract = function(xhr, xhrOptions) {
2015-05-26 10:13:20 +08:00
if (xhr.status === 500) {
throw new ServerError;
}
return extract ? extract(xhr.responseText) : (xhr.responseText.length === 0 ? null : xhr.responseText);
2015-05-26 10:13:20 +08:00
};
return m.request(options).then(response => {
this.alerts.dismiss(this.serverError);
return response;
}, response => {
this.alerts.dismiss(this.serverError);
if (response instanceof ServerError) {
this.alerts.show(this.serverError = new Alert({ type: 'warning', message: 'Oops! Something went wrong on the server. Please try again.' }))
}
throw response;
});
}
2015-05-18 16:43:16 +08:00
handleApiErrors(response) {
this.alerts.clear();
response.errors.forEach(error =>
this.alerts.show(new Alert({ type: 'warning', message: error.detail }))
);
}
route(name, params) {
var url = this.routes[name][0].replace(/:([^\/]+)/g, function(m, t) {
var value = params[t];
delete params[t];
return value;
});
var queryString = m.route.buildQueryString(params);
return url+(queryString ? '?'+queryString : '');
2015-04-25 20:58:39 +08:00
}
}
export default App;