Kardasis
Kardasis

Reputation: 941

Timers or timed events for backbone.js Views

I am trying to build an automatic carousel as a Backbone.js View so that it slides every so often. Ideally what I would like is a timer event. Something like

events{
  "timer 5000" : "slide"
}

I don't see this happening. I tried firing the function from the outside.

window.setInterval(carouselView.slide, 5000);

That works. BUT, I can't access the instance of the view anymore. If i do a console.log(this); it gives me Window. I guess this is because the function is being called from Window and not from the view instance.

Any help would be much appreciated.

Upvotes: 2

Views: 3191

Answers (2)

ivarni
ivarni

Reputation: 17878

I realize this is an old question by now but you can do this without binding.

(function(view) {
  window.setInterval(function() { view.slide(); }, 5000);
})(this);

If you stick that in your view's initialize it should work. What it does is basically creating a closure so that you still have access to the view inside your setInterval block.

I do agree that a timer event like "timer 5000" : "slide" would have been a nice feature for Backbone as I googled my way here looking for something exactly like that.

Upvotes: 3

topek
topek

Reputation: 18979

You have to bind the function to the context. I'm not 100% sure but I think this should work:

slide: _.bind(function(){ ... }, this)

See Backbone FAQ

Upvotes: 1

Related Questions