Backbone - populate json collection and view updates

I am trying to populate a collection with data from a JSON file. I am a beginner novice, so my problems are probably easy to solve. But they struggled with this all day - so now I ask for advice.

I am creating a questionnaire and want to download questions from a JSON file stored locally (I will receive questions from the server later).

I'm not sure if my collection is filling up at all, or if the problem is that the view is not updating. I read a lot of tutorials and got some ideas from different places.

Ok .. this is my javascript code:

$(function(){

var Question = Backbone.Model.extend({

    defaults: {
        q: "Empty question..."
    },

    initialize: function() {
        if (!this.get("q")) {
            this.set({"q": this.defaults.q});
        }
    }
});


var QuestionList = Backbone.Collection.extend({
    model: Question,
    url: "question.json"
});

var Questions = new QuestionList;


var QuestionView = Backbone.View.extend({

    tagName:  "li",

    template: _.template($('#item-template').html()),

    initialize: function() {
        _.bindAll(this, 'render', 'remove');
        this.model.bind('change', this.render);
    },

    render: function() {
        $(this.el).html(this.template(this.model.toJSON()));
        return this;
    }
});


var AppView = Backbone.View.extend({

    el: $("#questionnaire_app"),

    itemTemplate: _.template($('#item-template').html()),

    initialize: function() {
        _.bindAll(this, 'addOne', 'addAll', 'render');

        Questions.bind('reset',   this.addAll);
        Questions.fetch();
    },

    addOne: function(question) {
        var view = new QuestionView({model: question});
        this.$("#question-list").append(view.render().el);
    },

    addAll: function() {
        Questions.each(this.addOne);
    }
});

var App = new AppView;

});

And I have the following HTML code:

<div id="questionnaire_app">
    <div class="title">
        <h1>Questions</h1>
    </div>
    <div class="content">
        <div id="questions">
            <ul id="question-list"></ul>
        </div>
    </div>
</div>

<script type="text/template" id="item-template">
    <div class="question">
        <div class="display">
            <p class="question-content"><%= q %></p>
        </div>
    </div>
</script>

The JSON file is as follows:

[
    {
        "q": "How were your meeting with Dr. Apfelstrudel?"
    },
    {
        "q": "What do you think of the movie Die Hard 4.0"
    },
    {
        "q": "Are people from Mars really green?"
    }
]

: firebug, . console.log(Questions); , ReferenceError: . ?

: . -, ( ). .

+3
1

, , , .

: fiddle , , ( , jsfiddle). , JSON ( , ).

, firebug, , , -, .

var q = {};

$(function() {

  // Your code
  var Questions = new QuestionList;
   q.Questions = Questions
 //the rest of your code
});

firebug console.log(q.Questions);

+1

All Articles