Design pattern for bidirectional signals/events

This problem feels rather basic, yet I’ve never known a great solution. I’m looking for a way for components in an application to notify each other while being as decoupled as possible (both at build/compile and run time), but also avoiding circular notifications in a way that components do not need to self-mitigate against. I happen to be hitting this issue (for the hundredth time) in JavaScript right now, but that is incidental.

Some means of decoupling include:

  • Dependency injection (DI). In this case I use require.js which allows, for instance, substituting mock implementations in unit tests by creating alternate require.config() setups.
  • Event dispatching. E.g. fooInstance.listen('action string', barInstance.actionHandler)
  • Publish/subscribe (aka pub/sub).

The last two are basically variants of the Observer pattern with different pros and cons.

The problem I want to solve is not specifically addressed by these patterns, and I’m not sure if its an implementation detail or if there is a pattern to apply:

  • fooObj sends a message (fires an event, whatever) that the "baz" property has changed
  • barObj.bazChanged() handles this event by calling its own setBaz() method
  • barObj.setBaz() fires an event that “baz” has changed
  • fooObj.bazChanged() handles this event …

As a real case, imagine fooObj is a GUI component, with a slider for "tempo", and barObj is a music sequencing component that plays back a score. The slider should affect the tempo of the sequencer, but the score can contain tempo changes so when playing the sequencer should affect the slider position. A solution should be modeless.

One approach is to add guards, for example:

function handleTempoChanged(tempo) {
    if (this.tempo == tempo) return;
    ...
}

This works but feels like a poor solution because it means every event handler needs to either assume it needs a guard, which is ugly boilerplate and often not required, OR needs to be aware of the other components in the system that would make a cycle possible. Arguably, this point is wrong, guards should always be used if the handler is going to fire a changed event directly or indirectly, but this still feels like boilerplate logic. This may be the only answer to my question…

Is there general case pattern to deal with potential cycles as described? Note that this is not about synchronous vs. asynchronous; either way the cycles can occur.

EDITED to reflect insight from commenters:

I realize it is possible to eliminate the boilerplate, using some sort of mixin. In pseudo-code:

class ObservablePropsMixin:

    // generic setter with gaurd
    function set(propName, value):
        if this[propName] = value: return
        this[propName] = value
        _fire(propName, value) 

    // generic method to add listeners
    function observe(propName, handler):
        _observers[propName].add(handler)    

    // private event dispatching method
    function _fire(propName, value):
        foreach observer in _observers[propName]:    
            observer.call(propName, value)

    ...

This is simplified to focus on my question, but a real mixin would implement other pubsub or event or signal semantics, analogous to any event dispatcher implementation. Components needing to be observers or observables would inherit/extend from the mixin (the above assumes some form of multiple or aggregate inheritance is possible in the language. This could be modified to work with composition instead, e.g. ObservableMixin.constructor(observedObject) rather than using “this”.

2

The general solution to avoid repeating boilerplate is to pull it out into its own class. In this case, you would usually create a Publisher class that handles avoiding cycles for you.

var tempoPublisher = new NumericPublisher();

tempoPublisher.onTempoChange(moveTempoSliderWidget);
tempoPublisher.onTempoChange(changeSequencerTempo);

tempoSliderWidget.onSlide(function (percentage) {
    tempoPublisher.publish(percentage * maxTempo);
});

In your NumericPublisher.publish() you put your guard. Then no matter how many NumericPublishers or components you create, you only need the guard in one place.

This also breaks the dependencies of the components on each other. They only need to know about the tempoPublisher, which can be injected using DI.

1

A number of years ago, I had a similar problem in real time system design. The general approach I took was to create a set of modules with each module having a number of facets: inputs, outputs, control, maintenance, repository and a couple of others. Each module was assigned to a level in the system — sometimes the level was fairly arbitrary. In some cases, a module was split into parts, with lower level functions separated from higher level functions. In other cases, the facets were broken into levels (higher level inputs versus lower level inputs).

We established rules for how call-backs could be handled. The rules were based on directionality (up/down, left/right) and facets (inputs could only be connected to outputs). Rules were expressed as “this type of marble can only ever roll downhill” or “this ball can bounce higher”.

Model-View-Controller has a set of rules that are similar. In addition, within the JSP environment, there are timing rules: certain observations can only be made at certain times. The MVC framework itself imposes the rules.

In your case, it sounds like you are trying to build the framework yourself. Thus, you must establish the syntax and semantics of your “observer language”. Here is one approach you might want to play with:

Establish kinds of observations. The kinds are based on the impact of the observer on the state of the system. Establish relationships between kinds.

a) Display kind (View in MVC). The observed value is only ever formatted for viewing, and the value goes in only a single direction (towards the user, or towards a printed report).

b) Calculation kind. The observed value will take part in a calculation, likely with other observed values, and the result may, in turn, be observed. Circularity abounds and there must be infrastructure to identify convergence or divergence.

c) Input kind. User input such as form field or drop down. Result goes inward, towards the heart of the application. Display and Input kinds can be composed, of course, but they have a state relationship that prevents vicious circles.

d) Validater kind. Observes one or more values and rings a bell when things aren’t right. Inputs and Validaters can be composed, again with state and timing relationships

By establishing a protocol or language or rules of engagement, you may be able to retain your sanity. 🙂

4

The guards are only possible solution. There is no way some 3rd party code could distinguish between loop in event chain and normal event chain.

While the guards might seem as boilerplate logic, they are actually quite simple to implement some kinds of them can be abstracted away if language supports it. For example onChange could automatically check if the value changed and only fire the event if the value changes.

1

This is just a brief idea. I have not used or tested it myself.

In addition to a guard based on comparison of the current and the new value, circular notifications could be prevented by this scheme:

  • When a handler originates a property change, it asks the system for a unique event ID, and associate this property change with the event ID.
  • When another handler receives this property change, if it finds necessary to issue further property changes, it must “chain” the additional property changes with the original event ID, as well as attaching new event IDs to each additional property change. Thus, the event IDs will form a tree, with the original event at the root.
  • Each handler can store the event IDs it had finished processing, and thus prevent double-processing.

In some cases, a similar effect could be achieved by using a timestamp instead of a unique ID.

Note that this is a very heavy-weight option. I have not actually tested or used it, so it might not work as I had wished.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật