Search code examples
javascriptvariablesbackbone.js

Backbone cannot use this.el immediately after it is defined


I have a question about using variables immediately after they have been declared.

I have always tried to do things like this:

var BuzzQuizView = Backbone.View.extend({
    el: $('.buzz-quiz'),
    liveMarked: this.el.data('live-marked'),
    questionTotal: this.el.data('question-count'),
    quizId: this.el.data('quiz-id'),
    ...

Or if we take the issue away from Backbone I have always tried things like this:

var $answer = $('.answer'),
    $question = $answer.parent().parent();

But I always get an error, for the Backbone example it is:

Cannot read property 'data' of undefined

and in the case of the variables I get the error:

$answer is not defined

Why is this? I just cannot figure it out, why cant I use the variable? As I see it the variable has been declared, the code has executed so the variable should be available.

Any help would be hugely appreciated.

---- EDIT ----

So I have come that the normal JS example above using var does actually work perfectly.

What I was meant to be asking is why the same issue persists in any type of object take the following as an example:

var obj = {
    $body: $('body'),
    allDivs: $body.find('allDivs'),
    ...
}

Why is $body not available at this point?


Solution

  • this.el should be specified as jQuery selector string or DOM element. Not jQuery object, as in your code ($('.buzz-quiz')).

    Also this.el is undefined at the moment when you pass options to Backbone.View constructor. It is only available since Backbone.View is instantiated.

    So you have to initialize that properties inside Backbone.View constructor:

    var BuzzQuizView = Backbone.View.extend({
        el: '.buzz-quiz',
        initialize: function() {
            this.liveMarked = this.$el.data('live-marked');
            this.questionTotal = this.$el.data('question-count');
            this.quizId = this.$el.data('quiz-id');
        }
        ...
    });