Chris
Chris

Reputation: 1074

Debouncing Scroll using Ember.run.debounce

I have a working scroll mixin (that you can see in this gist).

http://jsbin.com/wofaj/4

App.Scrolling = Em.Mixin.create({
  bindScrolling: function() {
    var onScroll;
    var _this = this;

    var scrollFunc = function(){ 
       return _this.scrolled(); 
    };

    onScroll = scrollFunc;

    $(document).bind('touchmove', onScroll);
    $(window).bind('scroll', onScroll);
  },

  unbindScrolling: function() {
    $(window).unbind('scroll');
    $(document).unbind('touchmove');
  }
});

App.ApplicationView = Ember.View.extend(App.Scrolling, {
    didInsertElement: function() {
        this.bindScrolling();
    },
    willRemoveElement: function() {
        this.unbindScrolling();
    },
    scrolled: function() {
      console.log('MyView was scrolled : ' + document.body.scrollTop);
    }
});

But I believe it's recommended to debounce this, using the Ember run loop (specifically debounce - http://emberjs.com/api/classes/Ember.run.html#method_debounce).

Non-working code example here:

http://jsbin.com/wofaj/5

Problem code here:

onScroll = Ember.run.debounce(this, scrollFunc, 200);

Unfortunately no matter what context(s) I use I can't seem to get it working.

Some insight would be very much appreciated.

Thanks,

Chris

Upvotes: 2

Views: 2006

Answers (2)

Duncan Walker
Duncan Walker

Reputation: 2201

Another way to debounce functions in Ember is the following:

App.Scrolling = Em.Mixin.create({
    timer: null,

    scrollBinding: function() {
        this.set('timer', Em.run.debounce(this, this._scrollFunction, 100));
    },

    _scrollFunction: function() {
        // This function will run after 100ms after scrolling stops
    },
});

Upvotes: 0

melc
melc

Reputation: 11671

It will work if onScroll is assigned to a function,

onScroll = function(){Ember.run.debounce(this, scrollFunc, 200);};

http://jsbin.com/qoxulomo/1

Upvotes: 3

Related Questions