poseid
poseid

Reputation: 7156

Why 'undefined' after fetch via Backbone?

I've made a simple experiment to understand fetch on a model and fetch on a collection. However, this code gives 'undefined' for both:

    // Model and Collection
    var SingleItem = Backbone.Model.extend({
      urlRoot : '/data/item.json',
      parse: function(response) {
          console.log(response);
          return response;
      }
    });

    var ManyCollection = Backbone.Collection.extend({
      model: SingleItem,
      url: '/data/items.json',
    });

    var many = new ManyCollection();
    many.fetch();
    console.log(many);

    var single = new SingleItem();
    single.fetch({
      success: function(data) {
        console.log("OK"); 
        console.log(data.toJSON());
      },
      error: function(data){
        console.log("NOK");
      }
    });


    console.log(single.get('name'));

The demo is also here: https://github.com/mulderp/backbone-model-fetch

Why do I get 'undefined'? What am I missing?

(output from dev console:

dev output

Upvotes: 0

Views: 1004

Answers (1)

stusmith
stusmith

Reputation: 14113

fetch is asynchronous: it will return immediately, before the data has been fetched.

Moving the debug logic to inside the success handlers should fix the issue.

Upvotes: 3

Related Questions