avocado/packages/timing/src/timed-index.js

85 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-12-31 18:35:06 -06:00
import {Property} from '@avocado/core';
2022-03-11 05:08:59 -06:00
import {compose, EventEmitter} from '@flecks/core';
2020-12-28 21:18:54 -06:00
import Ticker from './ticker';
export default function TimedIndexMixin(indexName = 'index') {
return (Superclass) => {
2022-03-11 05:08:59 -06:00
const $$indexCount = `${indexName}Count`;
const $$indexRate = `${indexName}Rate`;
2020-12-28 21:18:54 -06:00
const decorate = compose(
EventEmitter,
Property('index', {
default: 0,
track: true,
}),
Property('isTicking', {
default: true,
}),
2022-03-11 05:08:59 -06:00
Property($$indexCount, {
2020-12-28 21:18:54 -06:00
default: 0,
}),
2022-03-11 05:08:59 -06:00
Property($$indexRate, {
2021-02-02 15:17:12 -06:00
default: 0.1,
get: function get() {
return this.ticker.frequency;
},
set: function set(frequency) {
this.ticker.frequency = frequency;
},
2020-12-28 21:18:54 -06:00
}),
);
return class TimedIndex extends decorate(Superclass) {
constructor(...args) {
super(...args);
2021-02-02 15:17:12 -06:00
this.ticker = new Ticker(0.1);
2020-12-28 21:18:54 -06:00
this.ticker.on('tick', this.onTick, this);
}
destroy() {
if (super.destroy) {
super.destroy();
}
this.ticker.off('tick', this.onTick);
}
get index() {
return super.index;
}
set index(index) {
2022-03-11 05:08:59 -06:00
super.index = 0 === this[$$indexCount] ? 0 : index % this[$$indexCount];
2020-12-28 21:18:54 -06:00
}
onTick() {
const index = this.index + 1;
2022-03-11 05:08:59 -06:00
if (index >= this[$$indexCount]) {
2020-12-28 21:18:54 -06:00
this.emit('rollingOver');
}
this.index = index;
}
reset() {
this.ticker.reset();
}
start() {
this.isTicking = true;
}
stop() {
this.isTicking = false;
}
tick(elapsed) {
if (this.isTicking) {
this.ticker.tick(elapsed);
}
}
};
};
}