2018-12-12 11:45:47 +01:00
|
|
|
/**
|
|
|
|
* Vue helper mixin to keep track if work is in progress or not.
|
|
|
|
* Example use:
|
|
|
|
* Keep track of work in own component:
|
|
|
|
* this.unitOfWork(
|
|
|
|
* thenDostuff()
|
|
|
|
* .then(...)
|
|
|
|
* .fail(...)
|
|
|
|
* );
|
|
|
|
*
|
|
|
|
* Keep track of work in child components:
|
|
|
|
* <myChild
|
|
|
|
* @unit-of-work="childUnitOfWork"
|
|
|
|
* />
|
|
|
|
*
|
|
|
|
* Use the information to enable class:
|
|
|
|
* <div :class="{disabled: 'isBusyWorking'}">
|
|
|
|
*/
|
|
|
|
var UnitOfWorkTracker = {
|
|
|
|
data() {
|
|
|
|
return {
|
|
|
|
unitOfWorkCounter: 0,
|
|
|
|
}
|
|
|
|
},
|
|
|
|
computed: {
|
|
|
|
isBusyWorking() {
|
|
|
|
if(this.unitOfWorkCounter < 0) {
|
|
|
|
console.error('UnitOfWork missmatch!')
|
|
|
|
}
|
|
|
|
return this.unitOfWorkCounter > 0;
|
|
|
|
}
|
|
|
|
},
|
|
|
|
watch: {
|
|
|
|
isBusyWorking(isBusy) {
|
|
|
|
if(isBusy) {
|
|
|
|
this.$emit('unit-of-work', 1);
|
|
|
|
} else {
|
|
|
|
this.$emit('unit-of-work', -1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
methods: {
|
|
|
|
unitOfWork(promise) {
|
|
|
|
this.unitOfWorkBegin();
|
2019-02-12 09:08:37 +01:00
|
|
|
if (promise.always) {
|
|
|
|
// jQuery Promise
|
|
|
|
return promise.always(this.unitOfWorkDone);
|
|
|
|
}
|
|
|
|
if (promise.finally) {
|
|
|
|
// Native js Promise
|
|
|
|
return promise.finally(this.unitOfWorkDone);
|
|
|
|
}
|
|
|
|
throw Error('Unsupported promise type');
|
2018-12-12 11:45:47 +01:00
|
|
|
},
|
|
|
|
unitOfWorkBegin() {
|
|
|
|
this.unitOfWorkCounter++;
|
|
|
|
},
|
|
|
|
unitOfWorkDone() {
|
|
|
|
this.unitOfWorkCounter--;
|
|
|
|
},
|
|
|
|
childUnitOfWork(direction) {
|
|
|
|
this.unitOfWorkCounter += direction;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-12 09:08:37 +01:00
|
|
|
export { UnitOfWorkTracker }
|