0

I'm new to BackboneJS. I try a demo of it, but messages.fetch() results nothing. And I override the Backbone.sync function to return a json, but messages.length always 0. Here is my code:

var Message = Backbone.Model.extend({});
var MessageStore = Backbone.Collection.extend({
    model: Message
});
Backbone.sync = function() {
    return [{"content":"Hi there","id":1},{"content":"How are you?","id":2}];
}
var messages = new MessageStore;
messages.fetch();
console.log(messages.length);          // 0
console.log(JSON.stringify(messages)); // []

I don't know where is wrong. Dose the response have to be a certain structure?

Prasanth A R
  • 4,046
  • 9
  • 48
  • 76
clark
  • 131
  • 1
  • 11
  • possible duplicate of [How to override Backbone.sync?](http://stackoverflow.com/questions/5096549/how-to-override-backbone-sync) – brandonscript Dec 19 '13 at 03:33

1 Answers1

2

Backbone.sync is used as a transport mechanism for read/write to the server, which can be customized by over-riding it, as described in the documentation. By default, Backbone.sync returns an XMLHttpRequest object.

Typically, fetch is an asynchronous call, but you threw that out the window, when you over-rode Backbone.sync, now all fetch returns is

[{"content":"Hi there","id":1},{"content":"How are you?","id":2}];

So if you did console.log(messages.fetch()); you would see the above content, but nothing is changed on the messages collection.

Let's pretend we didn't touch Backbone.sync for the following example, back on topic. I think you are looking for the parse method for a Backbone.Collection.

var Messages = Backbone.Collection.extend({
  url:'/someurl',
  parse:function(response) {
    // by default response is returned, but you can manipulate the response here.
    // given your example - we just return the static content - will be set on collection
    return [{"content":"Hi there","id":1},{"content":"How are you?","id":2}];
  }
});

//instantiate the new collection
var messages = new Messages();

messages.fetch({
  success:function() {
    console.log(messages.toJSON(),messages.length);
  }
});

Remember how I mentioned that fetch is asynchronous? When the request is complete, you want to check the results of fetch so that's why you need to supply a success callback.

You can see this demonstrated here.

fbynite
  • 2,651
  • 1
  • 21
  • 25