Question

I have a view in Backbone which has multiple functions. The functions I have are initialize, render, answer, answerQuestion, nextQuestion.

Here is the code I have in the initialize function

initialize: function(game) {
    _.bindAll(this, 'render', 'answer');
    this.render();
}

In the render function I call the answerQuestion function by doing this:

this.answerQuestion();

It works fine.

But in my answer function I call the nextQuestion function the same way and I get this error undefined is not a function, if I just call the function without the this at the start I get this error 'nextQuestion is not defined'

What am I missing to get this working. Here is the full answer function:

var v = $('.question.current .type').find('.input').val();

if (v !== undefined) {
    var t = new Date();
    var time_spent = t.getTime() - this.t.getTime();

    var self = this;
    answer.save().done(function(result, status) {
        if (status === 'success') {

            this.nextQuestion();

        }
    });
}
Was it helpful?

Solution

You're referring to the wrong context with: this.nextQuestion();. It should be self.nextQuestion();. Or you could bind the callback to the external function's context like this:

var v = $('.question.current .type').find('.input').val();

if (v !== undefined) {
    var t = new Date();
    var time_spent = t.getTime() - this.t.getTime();

    var self = this;
    answer.save().done(function(result, status) {
        if (status === 'success') {

            this.nextQuestion();

        }
    }.bind(this));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top