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

此生再无相见时 提交于 2019-12-06 06:22:05

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!