I’m building a filemanager using backbone.js. Its part of a CMS (content managament system) Im building, and is accessed via a lightbox/modal window. I need to show both files attached to a certain content type (like a post) and also all files in general.
At this point I have two separate collections, a libraryCollection (all files) and galleryCollection (a posts files). The first problem I’ve encountered with this method is: editing a file in the libraryCollection and binding a model change event to the view obviously doesnt affect the galleryCollection view.
Is there a better way to do this? Im thinking I will need pagination for the libraryCollection (as in REAL pagination with only xx number of results retrieved from the server) and this might complicate things. Unless loading potentially thousands of records into the collection is ok?
Update:
The quickest (possibly dirtiest) method was to use the built in Backbone.Events system. Sample code:
var aggregator = {};
_.extend(aggregator, Backbone.Events);
aggregator.on("fileUpdated", function(model){
if(app.libraryCollection && app.galleryCollection){
libraryModel = app.libraryCollection.get(model.get("id"));
galleryModel = app.galleryCollection.get(model.get("id"));
libraryModel.set(model.attributes);
galleryModel.set(model.attributes);
}
});
Then the Editor view:
window.EditorView = Backbone.View.extend({
saveModel: function(){
self = this;
form = $(this.el).find("form").serializeArray();
_.each(form, function(field){
self.model.set(field["name"], field["value"]);
});
self.model.save();
aggregator.trigger("fileUpdated", this.model);
}
});
This syncs the models across both collections, and because I bound the model change event with the render function (not shown) the view reflects the changes across both the library and gallery views.
One potential solution to your problem of communicating between separate Backbone.js components is to us an event aggregator. In the event aggregator pattern, components such as views will share a reference to an aggregator, which is an object that serves as a central communications hub for your application. Instead of a view subscribing to events on another view, both talk to the aggregator, which passes messages along to any component that subscribes for that type of message.
For example, your
libraryCollectionmight fire afileAddedevent on the aggregator, passing the newfileobject in the message. YourgalleryCollectionwould subscribe to thefileAddedevent on the aggregator, and it would take some action when it fires, such as refreshing itself from the server or adding the passedfileobject to itself.Here’s an excellent blog post that covers the event aggregator pattern.
Loading thousands of records into a collection at once sounds like a recipe for trouble.