How does MVVM really work? [duplicate]

5

How does MVVM really work? What are the responsibilities of ViewModel and Model?

I've been implementing a project with MVVM pattern for some time, but now some questions have come up about the pattern.

Where to implement the INotifyPropertyChanged interface? I've learned to implement it in ViewModel , but I see many examples implementing direct in Model .

Another question would be where to implement a code of the type in the example, in viewModel or Model . I would for example set the value of a int and save it in Backend shortly after.

public class ModelExample
{
  int items {get; set;}
}

public class ViewModelExample
{
  ModelExample modelExemplo {get; set;}

  ViewModelExample(ModelExample modelObject)
  {
    modelExemplo = modelObject;
  }

  //Implemento um metódo desse tipo na ViewModel ou na Model?
  public async Task Adicionar(){
    modelExemplo.Items++;
    //Salva no Backend do Azure (para ilustar o exemplo)
    AzureMobileServices.Instance.SaveDataAsync(modelExemplo);
  }
}
    
asked by anonymous 30.08.2016 / 18:22

1 answer

3

MVVM (Model-View-ViewModel)

As in this answer you already have the a basic explanation about the MVVM, I will not go into too many details. I'll focus more on your doubt.

For contextualization, MVVM is a UI-based design pattern, it is an MVP application, which is a derivation of MVC. The main objectives of the MVVM are: Flexibility, Ease of maintenance, Modularity, Testability and Rich UI (rich interface).

How does MVVM really work? What are the responsibilities of ViewModel and Model?

This image, taken from DevMedia , shows the MVVM architecture:

AViewisresponsiblefordefiningtheappearanceorstructurethattheuserseesonthescreen.WithpropertyDataContextitbindstoViewModel.

AViewModelisresponsibleformakingapresentationlogicavailabletoView.Ithasnospecificknowledgeaboutview,orhowitimplemented,noritstype.ItimplementspropertyandcommandssothatViewcanfillinitscontrolsandnotifyitifthereisanychangeofstate.ItimplementstheinterfaceINotifyPropertyChanged

Modelisresponsibleforencapsulatingbusinesslogicanddata,beingthedomainmodelofanapplication.Heisalsoresponsibleforvalidatingthedata.ItdoesnotreferdirectlytoVieworViewModel.AninterestingfeatureofmodelisthatitprovidesstatechangenotificationeventsthroughtheINotifyPropertyChangedandINotifyCollectionChangedinterfaces,makingiteasiertofilldataintheView.

WheretoimplementtheinterfaceINotifyPropertyChanged?

Inmyopinion,INotifyPropertyChangedshouldbeimplementedinViewModel,becausethisinterfaceonlyreportsachange.


References:

04.11.2016 / 15:31