簡體   English   中英

Backbone - 從json和更新視圖填充集合

[英]Backbone - populate collection from json and update view

我正在嘗試使用JSON文件中的數據填充集合。 我是骨干初學者,所以我的問題很容易解決。 但是整天都在努力 - 所以現在我要求指導。

我正在創建一個調查問卷,並希望從本地存儲的JSON文件加載問題(稍后我將從服務器獲取問題)。

我不確定我的集合是否完全填充,或者問題是視圖是否未更新。 我已經閱讀了很多教程,並從不同的地方得到了一些想法。

嗯..這是我的javascript代碼:

$(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;

});

我有以下HTML代碼:

<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>

JSON文件如下所示:

[
    {
        "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:沒有定義問題 這是為什么?

更新:問題解決了。 之前我沒有使用過Web服務器,我現在這樣做(我只是在瀏覽器中打開了文件)。 代碼工作正常。

我測試了你的代碼,它似乎運行得很好。

編輯 :這是一個鏈接到你的代碼的工作小提琴 ,只是修改,而不是獲取模型我手動添加列表(因為我沒有看到我如何在jsfiddle中復制它)。 也許你的問題是你的JSON文件(只讀,錯誤的位置)。

你在firebug中得到引用錯誤的原因是因為問題引用了文檔就緒函數末尾的范圍,如果你將它分配給你能夠記錄它的東西。

例如

var q = {};

$(function() {

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

現在,您可以使用console.log(q.Questions)將其記錄在firebug中;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM