Backbone.js - Filtering collections versus multiple collections

I am creating a filemanager using backbone.js. Its part of CMS (Content Management System) Im building and is accessible through the lightbox / mod window. I need to show both files attached to a specific content type (e.g. post) as well as all files in general.

At this point, I have two separate collections: libraryCollection (all files) and galleryCollection (message files). The first problem I ran into with this method is: Editing the file in the libraryCollection and binding the model change event to the view obviously doesn't affect the galleryCollection view.

Is there a better way to do this? I think I will need pagination for the libraryCollection (as in REAL pagination with only xx the number of results received from the server) and that might complicate things. If loading potentially thousands of records into a collection is ok?


The fastest (arguably dirtiest) method is 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"));


Then the editor's 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"]);
        aggregator.trigger("fileUpdated", this.model);


This keeps the models in both collections in sync, and since I linked the model change event to a render function (not shown), the view reflects changes in both the library view and gallery.


source to share

1 answer

One potential solution to the problem of communication between the individual components of Backbone.js is the event collector. In an event aggregator template, components such as views will have a link to the aggregator, which is an object that serves as the central communication hub for your application. Instead of a view that subscribes to events on a different view, both talk to an aggregator that passes messages along with any component that subscribes to that message type.

For example, yours libraryCollection

can fire an event fileAdded

on the aggregator by passing a new object file

in the message. Yours galleryCollection

will subscribe to the event fileAdded

in the aggregator, and if any action occurs, it will act, for example, update itself from the server or add the passed object file

to itself.

Here's a great blog post that covers the event aggregator pattern.

Uploading thousands of records to your collection immediately sounds like a recipe for trouble.



All Articles