Chris Cinelli
Chris Cinelli

Reputation: 4829

MarionetteJS: Using a collection with two or more views for different layouts

I have a UI controller that for simplicity you can think as a Folder Tree where you can select multiple folders with checkboxes. The selection is saved in the model and "on save" there rare also a few actions triggered.

For usability reasons, we want to use two different visualizations of the same controller. The two UI controllers can in some layouts be present at the same time, in others only one at the time.

It would be nice to be able to reuse the same collection instance across the 2 UI controllers.

I can do this in one module pretty easily but how should I structure the code to make it work across different modules? I was thinking of having a module with models and collection classes, one module with View1 and another with View2, but where is the best place to put the instance of the collection and make it communicate with the rest of the world.

What are the best practices to share Backbone Models/Collections instances with two or more Views in Marionette?

Upvotes: 2

Views: 1099

Answers (1)

David Sulc
David Sulc

Reputation: 25994

One approach is to have your entities (modules/collections) in a separate module, and have your various modules request them.

Example of an entity module (with collection definition and request handler): https://github.com/davidsulc/marionette-gentle-introduction/blob/master/assets/js/entities/contact.js#L89

Example of requesting a collection (line 7): https://github.com/davidsulc/marionette-gentle-introduction/blob/master/assets/js/apps/contacts/list/list_controller.js#L7

In your case, the same instance can be reused, if desired. But make sure you have some mechanism in place to display reasonably fresh data (i.e. fetching the collection on the server to get the most up to date data).

You can use javascript's closure mechanism to do so, e.g.:

ContactManager.module('Entities', function(...){
  var contacts = new Entities.ContactCollection(...);
  contacts.fetch();

  ContactManager.reqres.setHandler("contact:entities", function(){
    return contacts;
  });

  ContactManager.commands.setHandler("contact:entities:update", function(){
    return contacts.fetch();
  });
});

Then, in your app, you'd use ContactManager.request("contact:entities") to get the contacts, and ContactManager.execute("contact:entities:update").

The difference between a request and command is bascially semantic: requesting data from another part of the application, versus ordering some work to be done.

Using request-responses allows your application to be designed better (loose coupling, encapsulation). Attaching the data to App.SomeNamespace.mycollection will also work (I've done it in certain cases), but it leads to tight coupling, breaks encapsulation, and I wouldn't recommend it for large applications.

Upvotes: 3

Related Questions