François Richard
François Richard

Reputation: 7035

Backbone communication between views , a different pattern

I've read about mediator, event aggregator, using, backbone.events ...etc

I need advise about another potential pattern below, do you think this is evil ? or good ? if not good what are the caveats/problems.

This 'pattern' answers a very classical issue. When you click something on View1 , View2 has to render. View1 and View2 are independant (this is not a subview case). Between View1 and View2 we'll use an "Actions" module (yes more or less inspired by react/flux).

Here is the plan in pseudoCode:

View1:
     initialize:
        Actions.subscribe(this, 'view2);

View2:
     onclickwtv:
        Actions.displayView2();

Actions:
    this._Views = [];
    subscribe(view, viewName):
         this._Views[viewName] = view;

    displayView2:
         this._Views['view2'].render(); // or show or wtv function needed

When a view is removed we would call a unsubsribe function in actions that would pop the specific view off the _Views array.

The aim of this scheme is to have visibility on the different potential interactions between views (instead of an event aggregator where you don't have a central place to see those interactions).

Can't wait to read your thought about this!

Upvotes: 0

Views: 165

Answers (1)

76484
76484

Reputation: 8993

I would have View2 trigger an event on an Aggregator object:

onclickwtv: function () {
    Aggregator.trigger('wtc-click');
}

And I would have View1 subscribe to this event:

initialize: function () {
    this.listenTo(Aggregator, 'wtc-click', this.render);
}

Having View1 subscribe to Actions so that Actions can call View1.render() is just a roud-about way of achieving the same thing. Your solution has three decision-making objects, mine has only two. And my solution does not require management of the view states - a view will stop listening to the Aggregator when its .remove() method is called.

Upvotes: 1

Related Questions