Search code examples
javascriptbackbone.jsbackbone-views

backbone collection url


I use Backbone.js

I'm trying to get my data from server but it doesn't work

var Message = Backbone.Model.extend({});

var MessageStore = Backbone.Collection.extend({
    model: Message,
    url: myUrl
});

var messages = new MessageStore();
messages.fetch()
console.log(messages)

(server send json object)

I searched but no response

what's incorrect in my code?


Solution

  • Collection.fetch is an asynchronous operation. When you try to log the collection, the request is not yet complete, and the collection is still empty.

    You need to wait for the HTTP request to return. For that there's the success callback:

    var messages = new MessageStore();
    messages.fetch({
      success: function() {
        console.log(messages)
      }
    });