Take a look at this jsFiddle
Code also listed below:
window.MyView = Backbone.View.extend({
ticks: 0,
initialize: function() {
//window.setInterval(this.onTimerTick, 1000); // arghhh.. can't understand the 'this' scoping
window.setInterval(this.onTimerTick2, 1000); // Works great with globals
},
render: function() {
this.$el.text(this.ticks);
},
onTimerTick: function() { // Trouble with this
this.ticks++;
this.render();
},
onTimerTick2: function() { // Using globals
window.ticks2++;
$('#count').text(window.ticks2);
}
});
window.My = new MyView({ el: $("#count") });
window.ticks2 = 0;
Looking at the code, you see I would like to use the onTimerTick function, but becouse I can’t figure out how to get from the window-this to the My-this, I must use the approach seen in onTimerTick2. (usually I get around with a that=this, but in this case it is not enough)
Thanks for any attemt to make me understand this(!)
Thanks
Larsi
When passing
this.onTimerTick2to setTimeout, the function will be called withthisbeing bound to the global object, not your object.If underscore.js is available (according to @ori it is), you can use
_.bind()to lockthisto the correct object when called:Here are some solutions that do not depend on a library:
With a modern JS engine you can also use
Function.bind()to keep the correctthis: