Search code examples
c#mvp

How to signal presenters about changes deep in a complex model?


We're using MVP, but the problem itself isn't necessarily MVP-specific. Basically, presenters need to know if the model changes so they can process and reflect the changes to their view.

This would be easy using event in the model, but the model consists of other objects that are models too - they can be modified by a presenter+view that does not know about the root model or any of its presenters.

Here's a simplified example of such a model:

class Document
{
    Header header;
    List<Paragraph> paragraphs;
    Footer footer;
}

Let's say there are two presenters and views that create representations of the Document; DocumentEditPresenter/-View and DocumentPreviewPresenter/-View.

Then there would be ones for the model that the Document consists of; HeaderPresenter/-View, ParagraphPresenter/-View and FooterPresenter/-View.

DocumentEditPresenter would initiate creation of ParagraphPresenter/-View for a Paragraph after getting event from its view. This ParagraphPresenter would then modify the Paragraph - both DocumentEditPresenter and DocumentPreviewPresenter should get some sort of signal to refresh.

I know one solution would be that all the models contained references to their parents and/or events about every possible modification but it seems overly complicated and would make editing the models error-prone. Also the model should be serializable.

Something similar to WPF's routed events would be perfect.


Solution

  • If your model is deep ,it will be painful to listen to event coming from "the deep".

    I would organise my code with managers, acting like facade, so that any modification in the model,even deep, should go through one of the managers . Then, I would raise an event from the manager, and the presenter would listen to it.

    Your event could be just "ModelChanged" to trigger a refresh.