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

3

6

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.

Cleodel answered 21/4, 2012 at 6:56 Comment(0)
H
9

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'))
    }
});
Havard answered 21/4, 2012 at 7:0 Comment(0)
N
5

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()
});
Nonresistance answered 21/4, 2012 at 6:59 Comment(0)
V
1

Your "person_view" can not access any model (which is expected by that view) ,as no model is created yet, when you are declaring "person_view" and calling its function. First make a model then pass it to view when declaring that "person_view".

var model_person_for_view= new person();
var obj = new person_view(model:model_person_for_view);
obj.output();
Vernation answered 24/7, 2014 at 9:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.