Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communicating between views design patterns with events

event handlers are fine when you have a view that reference another view and listens its events, thats perfect for decoupling and reusability.

the problem though is sometimes I have views that is not referenced so I use Event Aggregator that is a global notification to know if something happened... but that seem not right when I just wanted to listen children views that I cant reference, something like bubbling events in the DOM hierarchy.

but let me say that I have a view hierarchy like:

  • ParentView
    • ChildView
      • ChildView
        • ModalView

I wanted to know in the ParentView when the ModalView triggers an event... I cant use event bubbling because the ModalView is not in the same DOM hierarchy, so should I use Event Agregator in this case or something else? I really wanted that event bubble could fits in my case.

like image 370
mateusmaso Avatar asked Nov 04 '22 03:11

mateusmaso


1 Answers

If you can't use the DOM's hierarchy and you don't want to use an event aggregator my first instinct is that you need to build your own hierarchy into your views.

You can take a look at backbone.courier for an idea of how to implement your own event bubbling system.

Backbone.courier uses the DOM to detect parent views but you can implement your own method for parent detection.

So it's doable without event aggregation or the DOM, but I think you'll end up creating and managing your own hierarchy. Since we have the DOM already, this smells. It would certainly make me question: "do I really need to bubble this event?".

For your example, the simplest solution might be to give your ModalView a reference to the ParentView and simply call the parentView.listener() when your even is fired on ModalView. Do you really need it to bubble through the children? Does this really need to be decoupled? It may be that you're being too restrictive when you assume you don't have a reference to your other view.

Those are questions I'd ask myself anyways. Though it may seem obvious it might be the best solution:

modalView.container = parentView;

modalView.myEventHandler = function(e) {
    this.container.myEventHandler(e);
}
like image 69
Dane O'Connor Avatar answered Nov 09 '22 05:11

Dane O'Connor