I am pretty new to Backbone and just came across this confusing issue. I am trying to fetch models in to my collection in a Express node.js server with the following code :
app.get('/tweet', function(req,res){
res.send([{ name: 'random_name' }, {name: 'diren_gezi'}] );
});
and my backbone code looks like this:
var PostsApp = new (Backbone.View.extend({
Collections: {},
Models: {},
Views: {},
}
start: function(){
var data = {
posts: [
{name:"gorkem"},
{name: "janish"},
{name: "akash"}
]
};
var posts = new PostsApp.Collections.Posts(data.posts);
var postsView = new PostsApp.Views.Posts({collection: posts});
posts.url = "/tweet";
posts.fetch();
console.log(posts.length);
console.log(posts);
}
}))({el : document.body});
I would expect console.log(posts.length) to return 5, because I am adding 3 when I initialize and 2 more when I fetch. Or even if the fetch method erases the collection and re-populates, I would expect posts.length to return 2. However it returns 3, but when I look into the post object from the console I only see two models, the ones coming from the fetch() method. What is the reason fror this ?

It is because , when you do a fetch the collection is reset
So the previous contents are removed and refreshed with the 2 new ones. That is the reason you see a length of 2.
Pass merge: true, to see a length of 5 , where in it effectively merges the collection
posts.fetch({merge: false});
because you already have declared data, and when you do fetch you return 2 more.
var data = {
posts: [
{name:"gorkem"},
{name: "janish"},
{name: "akash"}