Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access a models data from a view in backbone.js

I have a model named 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 an object of the view:

var obj = new person_view()

Try to access names:

obj.output()

But I got this error:

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

Can you show me how to do things properly?I've only just started getting to know backbone.js so please bear with me.

like image 942
Wern Ancheta Avatar asked Apr 21 '12 06:04

Wern Ancheta


2 Answers

You have to initialize your Model before you could access it :

var person_view = Backbone.View.extend({
    initialize: function() {
        this.model = new person();
    },
    output: function(){
        console.log(this.model.get('names'))
    }
});
like image 111
drinchev Avatar answered Oct 03 '22 23:10

drinchev


Instead of passing the model when you extend the view, you'll want to pass it when you construct 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()
});
like image 35
rjz Avatar answered Oct 03 '22 23:10

rjz