all files / couch/couch/changes/ suspendable-changes.js

92.31% Statements 24/26
80% Branches 8/10
100% Functions 6/6
92.31% Lines 24/26
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                                  11×                                               28× 28×          
import Ember from 'ember';
import Changes from './changes';
import { array } from '../../util/computed';
import assert from '../../util/assert';
 
const {
  computed: { gt },
  run: { next, cancel }
} = Ember;
 
export default Changes.extend({
 
  _suspended: 0,
  _queue: array(),
 
  isSuspended: gt('_suspended', 0).readOnly(),
 
  _trigger(...args) {
    if(this.get('_suspended') === 0 && this.get('_queue.length') === 0) {
      this.trigger(...args);
    } else {
      this.get('_queue').pushObject(args);
      this._enqueueFlush();
    }
  },
 
  _enqueueFlush() {
    cancel(this.__flush);
    this.__flush = next(this, this._flush);
  },
 
  _flush() {
    if(this.get('_suspended') > 0) {
      return;
    }
    var queue = this.get('_queue');
    var change = queue.shiftObject();
    Iif(change) {
      this.trigger(...change);
      this._enqueueFlush();
    }
  },
 
  _resume() {
    this.decrementProperty('_suspended');
    Eif(this.get('_suspended') === 0) {
      this._enqueueFlush();
    }
  },
 
  suspend() {
    this.incrementProperty('_suspended');
    let fn = () => {
      assert({ error: 'internal', reason: 'resume already called' }, !fn._called);
      this._resume();
      fn._called = true;
    };
    fn._called = false;
    return fn;
  },
 
  willDestroy() {
    cancel(this.__flush);
    this._super();
  }
 
});