Reputation: 687
I am used to Spine.js, but I want to try out Backbone.js.
In Spine, there are no collections. There are only models. In Spine, when I use a model in different places, Spine always keeps the models synced with each other when I update them. In Backbone, I find this not to be the case. I hope you can tell me what I am doing wrong!
I am trying to create 2 Articles collections which have 3 Article models inside them:
var Article = Backbone.Model.extend({});
var Articles = Backbone.Collection.extend({
model: Article,
localStorage: new Backbone.LocalStorage("Articles")
});
var articles1 = new Articles();
var articles2 = new Articles();
articles1.create({ id: 1, name: "Article 1" });
articles1.create({ id: 2, name: "Article 2" });
articles1.create({ id: 3, name: "Article 3" });
In Chrome I use the console and experiment a little:
articles1.size()
=> 3
articles2.size()
=> 0
articles2.fetch()
=> undefined
articles2.size()
=> 3
So far so good. The first Article in both collections is "Article 1":
a1 = articles1.first()
=> child
a2 = articles2.first()
=> child
a1.get("name")
=> "Article 1"
a2.get("name")
=> "Article 1"
But when I try to update the model in the first collection, it is not synced with the second collection:
a1.set({ name: "Article 1 - Updated" })
=> child
a1.save()
=> undefined
a1.get("name")
=> "Article 1 - Updated"
a2.get("name")
=> "Article 1"
I expected the model in the second collection to automatically update itself.
But I can see both article models have different cids:
a1.cid
=> "c0"
a2.cid
=> "c3"
So my question is... what do you do in Backbone? How do you keep models synced between collections?
I actually read this blog article: http://destroytoday.com/blog/reasons-for-spinejs/. He writes:
Dynamic Records
This one is just crazy black magic, but it solves a problem I faced with Backbone.js. Let’s say you fetched a record in one view of the app. Then you fetch and update that same record in a different view. In Spine.js, both records will update. You don’t have to worry about keeping them in sync. The moment I read about this, a single tear rolled down my cheek.
I have really tried to search about this but without luck.
I hope you can point me in the right direction on how to do this the Backbone way!
Upvotes: 2
Views: 1315
Reputation: 146064
You have 2 basic options:
Make sure both collections contain references to the exact same instances of models. Not just 2 objects with the same ID, but actually the same in-memory single model instance for that record.
Use the events bindings to try to keep either the collections or the models inside the collections in sync (add/remove/change/reset on collection1 in turn causes an add/remove/change/reset on collection2).
If you want the spine behavior, get #1 working. Perhaps use an instance cache as described here.
Upvotes: 3