smykes
smykes

Reputation: 312

.get() problems in Backbone

I have been struggling for this one for a while now, and thought I would just give in and ask here rather than continue to bang my head against my desk. This is pretty basic stuff, I am just starting with backbone. Why can't I access person via the .get() function?

I am using Mockjax for my ajax code and that looks like this:

$.mockjax({
    url: '/data',
    contentType: 'text/json',
    responseTime: 150,
    type: 'GET',
    responseText: '[{ "name": "Chance, Churc", "id_number": "", "w_time": null, "o_time": null }]'
});

and the Backbone portion:

var PWItem = Backbone.Model.extend({});
var person = new PWItem();
person.fetch({
    url: '/data',
    success: function() {
        console.log(person.attributes[0].name);  //this prints the correct attribute
    }
}):

console.log(person);  //prints the person object
console.log(person.get('name'));  //prints 'undefined'

Any help for a backbone noon would be appreciated.

Upvotes: 0

Views: 421

Answers (3)

Venkat Kotra
Venkat Kotra

Reputation: 10743

The mock ajax that you have written is for getting a collection of data. []. You can fetch the collection by hitting the url end point /data. You can define a collection and use as below.

 var PWItemColl = Backbone.Collection.extend({
    model: PWItem
    url: '/data'
    });

    var persons = new PWItemColl();
    persons.fetch ({
      success: function() {
       console.log(persons.at(0).get('name')); // "Chance, Churc"
      }
    });

Upvotes: 0

Paul Hoenecke
Paul Hoenecke

Reputation: 5060

You have two problems.

Return single object instead of an array.

$.mockjax({
    url: '/data',
    contentType: 'text/json',
    responseTime: 150,
    type: 'GET',
    // you are fetching a single model, so JSON should not be an array
    responseText: '{ "name": "Chance, Churc", "id_number": "", "w_time": null, "o_time": null }'
});

Wait until fetch is complete to access the attributes.

var PWItem = Backbone.Model.extend({});
var person = new PWItem();
person.fetch({
    url: '/data',
    success: function() {
       // this will only work after success
       console.log(person.get('name')); // should print "Chance, Churc"
    }
}):

person.on('change:name', function(){
    console.log(person.get('name')); // should print "Chance, Churc"
});

console.log(person);  //prints the person object
// fetch is not done yet, 'undefined' is expected.
console.log(person.get('name'));  //prints 'undefined' 

Upvotes: 2

Thiago Pontes
Thiago Pontes

Reputation: 606

Have you tried like this?

$.mockjax({
    url: '/data/1',
    contentType: 'text/json',
    responseTime: 150,
    type: 'GET',
    responseText: '{ "name": "Chance, Churc", "id_number": "", "w_time": null, "o_time":     null }'
});


var PWItem = Backbone.Model.extend({});
var person = new PWItem({url: '/data', id: 1});
person.fetch();
console.log(person.get('name'));

Upvotes: 0

Related Questions