0

We have a backbone.js application that needs to have a shared context model storing the environmental variables of the application, which can trigger events in multiple views. An easy way to do is to use the same model across multiple views, serving like a global object. But I have two issues with this design: first, it seems to be a bad design pattern using a global variable; second, it forces all views to use the same model, which created the undesirable strong coupling between views even though each view can be set to listen a subset of the model attributes.

One solution that I am considering is that a child view can have his own model with this shared context model as one of its attributes.

I am new to backbone.js, so I am wondering what other alternative solutions people are using.

HZhang
  • 175
  • 12
  • How about creating a global event bus, and any view can subscribe/publish event in it if needed. http://stackoverflow.com/questions/20181679/call-a-function-in-another-marionette-itemview/20182584#20182584 – Yurui Zhang May 08 '14 at 18:34
  • It seems like a good alternative. The only thing is that the event bus or the event aggregator requires the detailed definition of the event bus, the event name, provider, and consumer, one by one, while the shared model object is simpler as we can just put everything in the object. – HZhang May 29 '14 at 05:40
  • hm...you don't really need to do that. you can easily define a simple event object (e.g. `App.Events`) and subscribe by `this.listenTo(App.Events, 'eventname', this.eventHandler)`, or publish events by `App.Events.trigger('eventname', [event-data])` App.Events does not have to know anything about the name, provider, or consumer. – Yurui Zhang May 29 '14 at 20:23

1 Answers1

1

Take a look at backbone.wreqr, which contains a global event aggregator and is a part of the great Backbone.Marionette library.

Then you can share the event aggregator instance between the views and have them listen to events triggered from the environmental variables module.

Eran C.
  • 61
  • 3