,debouncedAjax: _.debounce(_.bind(myFunction, this), 2000)
,request: function(requestParams, response){
this.debouncedAjax(requestParams, response);
}
when I can request, I get this
Uncaught TypeError: Cannot call method ‘apply’ of undefined
(anonymous function)
If i set the result of that debounce function on the debouncedAjax property like this
,initialize: function() {
this.debouncedAjax = _.debounce(this.imoveisAjaxRequest, 2000);
}
It works fine !
WHY ?
BTW: debounce is a function from the AMAZING underscore.js framework !
As so many things in Javascript, it comes down to what the
thispointer means.In the first instance, you’re probably defining a class prototype. If not explicity, then inside a Backbone.something.extend() call, which is the same thing. At that point, you’re binding a function with
_.bind(myFunction, this). So what does thethispointer refer to at that point? It’s certainly not any particular instance of the object, because they haven’t been created yet. It’s probably eitherwindowor something in the Backbone framework.When you call that function in the
initializefunction, thethispointer means what you want it to, so everything works out as you want it to.