Reputation: 12857
In my main.js, i have a chunk that I can separate into its own module that sets the timezone for the user after an api call, and regardless of the ajax call (success or fail), I initialize my Vue instance.
main.js:
import * as moment from 'moment-timezone/moment-timezone';
moment.tz.setDefault("UTC");
window.Vue.prototype.moment = moment;
let timezone = "UTC";
let userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
axios.get('/api/timezone-data', {
params: {
timezone: userTimezone
}
}).then(response => {
// do other stuff
initVue();
}).catch(error => {
initVue()
});
// Separate until here into its own module
function initVue() {
// initialises vue
}
I want to learn how can I move this chunk into its separate file and somehow be able to catch when it triggers the initVue()
methods.
Something like, in my main.js:
require('./tz-settings').then(() => {
console.log('initVue() is called')
})
Or to be more clear,
import tzSettings from './tz-settings';
tzSettings('initVueCalledInTzSettings', () => {
initVue();
})
Upvotes: 2
Views: 895
Reputation: 1
One possible solution:
Based on the comment that initVue is in main.js
import * as moment from 'moment-timezone/moment-timezone';
export default function(initVue) {
moment.tz.setDefault("UTC");
window.Vue.prototype.moment = moment;
let timezone = "UTC";
let userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
return axios.get('/api/timezone-data', {
params: {
timezone: userTimezone
}
}).then(response => {
// do other stuff
initVue();
}).catch(initVue);
};
of course you could also use Promise .finally
}).then(response => {
// do other stuff
}).catch(error => {
// handle the error in some way
}).finally(initVue);
And you would use it like
import tzsettings from './tz-settings.js';
tzsettings(initVue).then(() => {
console.log('initVue() is called')
})
Though to be honest, why not do
export default function() {
moment.tz.setDefault("UTC");
window.Vue.prototype.moment = moment;
let timezone = "UTC";
let userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
return axios.get('/api/timezone-data', {
params: {
timezone: userTimezone
}
}).then(response => {
// do other stuff
});
};
and use it like
import tzsettings from './tz-settings.js';
tzsettings().finally(initVue);
Why does tz-settings
need to know anything about initVue
at all
Upvotes: 4