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.