dzm
dzm

Reputation: 23554

Backbone.js bind this to setInterval

I'm trying to access this.collection from within a setInterval. However, this isn't bound. I can't seem to figure out how to bind it so that this can access the collection, not the setInterval object.

Here's a snipit from my View.

initialize: function(){
  _.bindAll(this);
},
start: function() {
  setInterval(function() {
    this.collection.each(function(item) { 
      console.log(item.id);
    });
  }, 5000);
}

Any suggestions?

Upvotes: 4

Views: 3158

Answers (2)

mvbl fst
mvbl fst

Reputation: 5263

You can do this:

initialize: function(){
  _.bindAll(this);
},
afterInterval: function() {
  this.collection.each(function(item){ 
    console.log(item.id);
  });
},
start: function() {
  setInterval(this.afterInterval, 5000);
}

afterInterval is now a callback and it has access to this of the view.

Upvotes: 4

millimoose
millimoose

Reputation: 39970

You should bind() the value of this you need when you set up the callback:

setInterval(function() {
    this.collection.each(function(item) { 
        console.log(item.id);
    });
}.bind(this), 5000);

Don't forget to include the shim from the above MDN page if you need IE8 compatibility.

Upvotes: 8

Related Questions