Backbone.js - Models not being passed into view for template use -
i new @ backbone.js(and js in general) , have been experimenting storing model data in .json file. keep getting error:
uncaught typeerror: cannot call method 'tojson' of undefined
caused by:
var questionview = backbone.view.extend({ tagname:"div", classname:"question-container", initialize:function() { _.bindall(this, "render"); console.log(this.model); //logs undefined models being fetched successfully? console.log("questionview created"); this.render(); }, render: function() { var data = this.model.tojson(); //this line throwing error var source = $("#question-template").html(); var template = handlebars.compile(source); $(this.el).html(template(data)); return this; } });
i can see in console models there don't understand i'm doing wrong.
in context:
$(function() { //question model var question = backbone.model.extend({ initialize: function() { console.log("question created"); }, defaults:{ number:"", title:"", answera:"", answerb:"", answerc:"", answerd:"" } }); //questions collection var questions = backbone.collection.extend({ url:"data/questions.json", model:question, initialize: function() { console.log(this); } }); //question view var questionview = backbone.view.extend({ tagname:"div", classname:"question-container", initialize:function() { _.bindall(this, "render"); console.log(this.model); console.log("questionview created"); this.render(); }, render: function() { var data = this.model.tojson(); var source = $("#question-template").html(); var template = handlebars.compile(source); $(this.el).html(template(data)); return this; } }); //questions view var questionsview = backbone.view.extend({ el:"#app-view", initialize: function() { console.log("questionsview created"); this.collection = new questions(); this.collection.fetch({reset:true}); this.collection.on('reset', this.render, this); }, render: function() { var questionview = new questionview(); $(this.el).append(questionview); return this; } }); var questionsview = new questionsview(); });
you're not sending actual instance of model questionview
. you'll need this:
render: function() { var self = this; _.each(this.collection, function(model) { var questionview = new questionview({ model: model }); $(self.el).append(questionview); }); return this; }
Comments
Post a Comment