Say, for example, I want to write an API modelling a countdown that cannot be restarted.
I might write something like the following (shared method implementations at bottom):
const countdown = { start, stop };
function start(options) { // Options contains `duration` and `done`.
this.startTime = performance.now();
Object.assign(this, options);
this.id = requestAnimationFrame(tick.bind(this));
}
// Usage
const myCountdown = Object.create(countdown);
myCountdown.start({ done, duration: 1000 });
myCountdown.stop();
But, this leaves a redundant start
method on myCountdown
while the countdown is in progress.
So I might rewrite this like so:
const inProgressCountdown = { stop };
const countdown = { start };
function start(options) { // Options contains `duration` and `done`.
var c = Object.create(inProgressCountdown);
c.startTime = performance.now();
Object.assign(c, options);
c.id = requestAnimationFrame(tick.bind(c));
return c;
}
// Usage
const myCountdown = countdown.start({ done, duration: 1000 });
myCountdown.stop();
In this way the running countdown does not have a redundant start method on it.
Is this a valid approach and is there a name for this approach/implementation pattern?
Shared method implementations:
function stop() {
cancelAnimationFrame(this.id);
}
function tick(now) {
if ((now-this.startTime) >= this.duration) {
return this.done();
}
this.id = requestAnimationFrame(tick.bind(this));
}
function done() {
alert('done');
}
Aucun commentaire:
Enregistrer un commentaire