I have a backbone model that looks somewhat like this:
var myModel = Backbone.Model.extend({
watch : function() {
this.watcher = setInterval("this.refetch", 5000);
}
refetch : function() {
//do something
}
});
The setInterval method doesn’t actually work, because, I suppose, this.refetch isn’t valid in the setInterval call. Neither does setInterval("refetch", 5000); work.
What I’m doing right now is this:
watch : function() {
var that = this;
setInterval(function(){
that.refetch();
}, 5000);
}
Is there a better way to do this, so that I don’t need to use that.
Since Backbone already brings underscore.js with it, use it. In your case, context can be bound to interval function with
_.bind:This is better approach not only because it’s shorter, but also because it prevents
thatalias from beeing visible in nested scopes which can cause all sorts of hard-to-catch bugs. See idiomatic.js style guide, “Faces of this” section: https://github.com/rwldrn/idiomatic.js/