2

I'm trying to use _.throttle in an object but I think I haven't understand how to do this correctly.

I use jQuery and Underscore.js

function object() {
    this.throtthled = function () {
        // This should alert 1
        alert(this.var);
    }

    this.fastFunc = _.throttle(this.throtthled, 100);
    this.var = 1;
}


$(function () {    
    var myObject = new object();
    $(document).on('mousemove', myObject.fastFunc);    
});

But as you can see on this jsfiddle, this only returns undefined in console. What am I doing wrong ?

Hugo H
  • 6,029
  • 5
  • 37
  • 57

1 Answers1

4

You're accessing this.throtthled before having created it, passing undefined to _.throttle instead of a function (which had an .apply method).

Also, you need to use the correct this context for your callback.

// using the prototype:
function MyObject() {
    this.fastFunc = _.throttle(this.throttled.bind(this), 100);
    this.var = 1;
}
MyObject.prototype.throttled = function () {
    // This does alert 1
    alert(this.var);
};
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • It works! Thanks. What if I want to give fastFunc a parameter ? – Hugo H Dec 01 '14 at 20:44
  • 1
    Just give `throttled` a parameter. `_.throttle` passes any given arguments through. – Bergi Dec 01 '14 at 20:45
  • Thanks a lot. I'll have a deeper look at Prototype. – Hugo H Dec 01 '14 at 20:59
  • The prototype is not actually required for this solution, you just have to take that method from somewhere (prototype, static variable, constructor-defined function etc) and `bind` it – Bergi Dec 01 '14 at 21:28