Advertisement
Guest User

Untitled

a guest
May 26th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. export default class Updater {
  2. constructor(options) {
  3. this.options = Object.assign({}, Updater.DefaultOptions, options || {});
  4.  
  5. this.callbacks = [];
  6.  
  7. this.start = Date.now();
  8. this.last = Date.now();
  9.  
  10. this.interval = setInterval(() => this.update(), this.options.updateRate);
  11. }
  12.  
  13. static install(Vue, options) {
  14. let instance = Vue.prototype.$updater;
  15. if (!instance) {
  16. instance = new Updater(options);
  17. }
  18.  
  19. Vue.prototype.$updater = instance;
  20. }
  21.  
  22. addListener(callback) {
  23. if (-1 !== this.callbacks.indexOf(callback) && (true !== this.options.mute)) {
  24. console.warn('Duplicate updater handler detected.');
  25. }
  26.  
  27. if (typeof(callback) !== 'function') {
  28. throw new Error('Expected argument one to be a function, got ' + typeof(callback));
  29. }
  30.  
  31. this.callbacks.push(callback);
  32. }
  33.  
  34. removeListener(callback) {
  35. do {
  36. let index = this.callbacks.indexOf(callback);
  37. if (-1 !== index) {
  38. this.callbacks.splice(index, 1);
  39. }
  40. } while(-1 !== index);
  41. }
  42.  
  43. update() {
  44. const now = Date.now();
  45.  
  46. const deltaTime = now - this.last;
  47. const fromStart = now - this.start;
  48.  
  49. for (let k in this.callbacks) {
  50. this.callbacks[k].call(this, deltaTime, fromStart, now);
  51. }
  52.  
  53. this.last = now;
  54. }
  55. }
  56.  
  57. Updater.DefaultOptions = {
  58. updateRate: 33
  59. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement