0

I made a quiz with jQuery, very poorly coded. And now im recoding it using OOP. However, I have a problem storing JSON information into my model property.

var quizModel = {
    currentQuestion: 0,
    correctAnswers: 0,

    init: function() {
        "use strict";
        $('.quiz').append('<div class="form"></div>');
        $('.form').append('<form id="form"></form>');
        quizView.addQuestion();
    },
    getJson: function() {
        "use strict";
        return JSON.parse($.ajax({
            type: 'GET',
            url: 'package.json',
            dataType: 'json',
            global: false,
            async:false,
            success: function(data) {
                return data;

            }
        }).responseText);
    },
    answerDatabase: this.getJson()
};

I cant store the JSON object into the answerDatabase property. And I dont know why. When I wasnt using OOP I was able to do store the returned object into a variable and have access to that object across my javascript file. Anyone have a clue how to fix this? The console says (Uncaught TypeError: Cannot read property 'getJson' of undefined)

idontknow
  • 966
  • 8
  • 21
  • 1
    Related: http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations – Stryner Jan 21 '15 at 18:55

1 Answers1

2

answerDatabase: this.getJson() is being called before your object definition is complete, so in scope this is probably the window object. You will need to restructure your code to something like (this is not a perfect example)

var quizModel = {
    currentQuestion: 0,
    correctAnswers: 0,

    init: function() {
        "use strict";
        $('.quiz').append('<div class="form"></div>');
        $('.form').append('<form id="form"></form>');
        quizView.addQuestion();
    },
    getJson: function() {
        "use strict";
        return JSON.parse($.ajax({
            type: 'GET',
            url: 'package.json',
            dataType: 'json',
            global: false,
            async:false,
            success: function(data) {
                return data;

            }
        }).responseText);
    },
    answerDatabase: {};
};

quizModel.answerDatabase = quizModel.getJson();
lemieuxster
  • 1,081
  • 7
  • 14
  • Thanks, that worked. I didnt like the fact that it is outside my object, so i stored it in my quizController object instead! (answerDatabase: quizModel.getJson()) Works as intended. – idontknow Jan 21 '15 at 18:55