The problem is with the Backbone model.fetch () callback (setTimeout call)

I have a main view (Services) with a list of child views (Service). Each type of childhood should be updated every 5 seconds. For this, I had the following [extract]:

Service: Backbone.View.extend({ ... initialize: function () { this.model.bind('change', this.render, this); _.bindAll(this, 'update'); }, render: function () { ... this.update(); return this; }, update: function() { this.model.fetch(); setTimeout(this.update, 5000); } ... 

Calling setTimeout on update() , of course, worked like this , correctly associated with the view in question.

The problem occurs when I move setTimeout to a callback for fetch , since this now points to the global scope:

  update: function() { this.model.fetch({ success: function() { // this is now global setTimeout(this.update, 5000); }}); } 

How can I get a continuous (non-overlapping) update function. Or - how can I apply a viewport to this inside a fetch callback?

Update

Just went over this old question, and for future reference, I am following this template now, as I find _.bind OTT here:

  update: function() { var self = this; this.model.fetch({ success: function() { setTimeout(self.update, 5000); }}); } 
+7
source share
2 answers

One option is to use the Underscore _.bind function:

 update: function() { this.model.fetch({ success: _.bind(function() { setTimeout(this.update, 5000); }, this)}); } 
+21
source

I know this is an old question, but success and failure events return three values: model, answer, and parameters. Instead of calling this.update in the success function, you can call model.update :

 update: function() { this.model.fetch({ success: function( model, response, options) { setTimeout(model.update, 5000); }}); } 
+6
source

All Articles