javascript - Can't bind collection to view -
how bind collection view? when debug can't use this.collection.get() or this.collection.at() in quizview
my code - http://jsfiddle.net/zqyh5/
html
<div class="row" id="quizs"> <script type="text/template" id="quiztemplate"> < h1 ><%= title %>< /h1> </script> </div> <button id="next">next</button>
javascript
$(function () { var quiz = backbone.model.extend({}); var quizlist = backbone.collection.extend({ model: quiz }); var quizs = {[{id: 1, title: "a"},{id: 2,title: "b"},{id: 3,title: "c"},{id: 4,title: "d"},]} var questionview = backbone.view.extend({ events: { 'click #next': 'shownextquestion' }, collection: quizs, initialize: function () { _.bindall(this, "shownextquestion", "render"); this.currentindex = 0; this.render(); }, shownextquestion: function () { this.currentindex++; if (this.currentindex < this.collection.length) { this.render(); } }, render: function () { var template = _.template($("#quiztemplate").html(), this.collection.at(this.currentindex)); this.$el.html(template); }, }); var app = new questionview({}); })
updated fiddle: http://jsfiddle.net/gijsjanb/zqyh5/2/
<script type="text/template" id="quiztemplate"> <h1><%= title %></h1> </script> <div id="myquiz"> <div class="row" id="quizs"></div> <button id="next">next</button> </div>
and
$(function () { var quiz = backbone.model.extend({}); var quizlist = backbone.collection.extend({ model: quiz }); var quizs = [{ id: 1, title: "a" }, { id: 2, title: "b" }, { id: 3, title: "c" }, { id: 4, title: "d" }]; var questionview = backbone.view.extend({ events: { 'click #next': 'shownextquestion' }, initialize: function () { this.currentindex = 0; this.render(); }, shownextquestion: function () { this.currentindex++; if (this.currentindex < this.collection.length) { this.render(); } }, render: function () { var template = _.template($("#quiztemplate").html(), this.collection.at(this.currentindex).tojson()); this.$('#quizs').html(template); } }); var app = new questionview({ el: $('#myquiz'), collection: new quizlist(quizs) }); });
there issues:
- you have pass instantiated collection view or instantiate in view's initialize function.
- the
<button>
outside views scope. - move
<script>
out of views scope. - the quizs var gives error: object not know array.
{[]}
gives error,{myarr: []}
not. quizs should array, not object.
Comments
Post a Comment