How to access model data from a view in backbone.js

I have a model called person:

var person = Backbone.Model.extend({ initialize: function(){ console.log('cool'); }, defaults:{ names:['a','k','d','s','h','t'] } }) 

Now I have a view:

 var person_view = Backbone.View.extend({ model : person, output: function(){ console.log(this.model.get('names')) } }); 

Created a view object:

 var obj = new person_view() 

Try accessing the names:

 obj.output() 

But I got this error:

 TypeError: Object function (){ parent.apply(this, arguments); } has no method 'get' 

Can you show me what to do? I just started getting acquainted with backbone.js, so please bear with me.

+7
source share
3 answers

You must initialize your model before you can get it:

 var person_view = Backbone.View.extend({ initialize: function() { this.model = new person(); }, output: function(){ console.log(this.model.get('names')) } }); 
+9
source

Instead of passing the model when viewing extend , you will want to pass it when creating a new view:

 var person_view = Backbone.View.extend({ output: function(){ console.log(this.model.get('names')) } }); var obj = new person_view({ model : new person() }); 
+5
source

Your person_view cannot access any model (which is expected in this view), because the model has not yet been created when you declare person_view and call its function. First create a model, then pass it to view when declaring this "person_view".

 var model_person_for_view= new person(); var obj = new person_view(model:model_person_for_view); obj.output(); 
+1
source

All Articles