andrewohyeah
4/6/2014 - 4:40 PM

Ember Observers debounced and throttled. Concept from http://alexspeller.com/2013/08/09/Debounced_and_Throttled_Observers_in_Ember.html but

Ember Observers debounced and throttled. Concept from http://alexspeller.com/2013/08/09/Debounced_and_Throttled_Observers_in_Ember.html but modified to include an arbitrary number of object observation keys

Ember.debouncedObserver = function() {
  var args = Array.prototype.slice.call(arguments),
      fn = args[0],
      time = args.reverse()[0],
      keys = args.slice(1, args.length-1);

  var debouncer = function() {
    Em.run.debounce(this, fn, time);
  };
  var newArgs = [debouncer];

  keys.forEach(function(item){
    newArgs.push(item);
  });
  
  return Em.observer.apply(this, newArgs);
};

Ember.throttledObserver = function() {
  var args = Array.prototype.slice.call(arguments),
      fn = args[0],
      time = args.reverse()[0],
      keys = args.slice(1, args.length-1);

  var throttler = function() {
    Em.run.throttle(this, fn, time);
  };
  var newArgs = [throttler];

  keys.forEach(function(item){
    newArgs.push(item);
  });
  
  return Em.observer.apply(this, newArgs);
};