JSON 파일의 데이터로 콜렉션을 채우려고합니다. 나는 백본 초보자이기 때문에 문제는 쉽게 해결할 수 있습니다. 그러나 하루 종일 힘들어했습니다. 그래서 지금 저는 도움을 청하고 있습니다.백본 - json에서 콜렉션 채우기 및 업데이트보기
설문지를 작성 중이고 로컬에 저장된 JSON 파일에서 질문을로드하고 싶습니다. 나중에 서버에서 질문을 받게됩니다.
내 모음집이 전혀 채워지거나보기가 업데이트되지 않는다고 확신 할 수없는 경우 확실하지 않습니다. 나는 많은 튜토리얼을 읽고 여러 곳에서 아이디어를 얻었습니다.
음 .. 이건 내 자바 스크립트 코드 :
$(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?"
}
]
을 보너스 질문 : 방화범이 끌리지 만이 문제를 디버그하는 것은 매우 어렵습니다. 물건. 예를 들어 콘솔에 console.log(Questions);
이라고 쓰면 ReferenceError : 질문이 정의되지 않았습니다. 왜 그런가요?
업데이트 : 문제가 해결되었습니다. 전에는 웹 서버를 사용하지 않았습니다. 브라우저에서 파일을 열었습니다. 코드가 제대로 작동합니다.
새로운 QuestionList()는 prob입니다. 참조 오류 – Alex
@Alex에 대한 해결책 마지막에()를 추가 할 필요가 없습니다. – Jack
누락 된 코드가 있습니까? 코드가 정상적으로 실행됩니다. – Jack