How do you handle change tracking in MVVM? - mvvm

I have written a small helper for doing client-side change tracking objects/dtos to use in my ViewModels (see http://viss.be/2009/04/02/modelviewcontext-client-side-change-tracking/)
I didn't find a lot of resources about the subject. So I wonder; how do you typically handle it?
Thanks,
Marc

A ViewModel is all about binding the View (UI) to the Model (data). So it should not be responsible for tracking changes, that is something you should be doing inside of you Model classes as they contain the data.
To notify the UI both Model and ViewModel implement INotyfyPorpertyChanged. The ViewModel catches the Model events and propagates them to the View as needed.
See http://msmvps.com/blogs/theproblemsolver/archive/2009/04/07/using-model-view-viewmodel-with-silverlight.aspx for a more complete example.

I didn't find a lot of resources about
the subject.
I too want to see more discussion on this topic
So I wonder; how do you typically handle it?
Just use DataSet.
Keep looking for solutions.

Related

How is a Model supposed to signal change? via events? via mediator/eventaggregator? via INPC?

Suppose upon a button click in the View, the ViewModel calls an asynchronous, long and tough calculation on the Model (with Model being business logic and data, as per Wikipedia). During this calculation the Model is spitting out one calculation result after the other (which are of a different kind, it's not like an ObservableCollection is useful here) and the View is supposed to display them the moment these part-results are ready.
How can it do that?
Via an EventAggregator? Caliburn Micro has one but that would mean I had to reference Caliburn Micro in my business logic - this can't be right, can it?
Via INPC? I have the impression that wherever I implement INPC, that class is going to be exposed to be bound to. I obviously wouldn't want a class with business logic exposed to the View just so I can bind to some of it's properties. So I'd need an indirection with a separate class (implementing INPC) whose properties I set from the business logic that the View can bind to. Now what I have done feels like creating a ViewModel that the model is tied to. - this can't be right either! (Not exposing it, but wrapping it with a ViewModel subscribing to PropertyChanged feels like a pretty severe violation of DRY)
So I guess I need to use plain old events? Having read Mark Seemans book and blog on DI I have the impression this is wrong too. Since subscribing to an event in the constructor is wrong. His suggestion is to reverse the logic and let the DI container inject an IObserver<> into the business model class, which will call Next() on it. That would mean the ViewModel will implement potentially quite a few IObserver<> interfaces? Is that it?
I need a bit of guidance here, thanks!

Does knockout.js really employ MVVM pattern?

I am new to knockout.js. Few moments back I read the headline features of ko.
I could not understand is ko really MVVVM? Because all they talk about is data binding and the ease of it. But I am sure MVVM is more than data binding isn't it?
Yes, knockout.js does apply the MVVM pattern. It's explained in the documentation:
A model: your application’s stored data. This data represents objects and operations in your business domain (e.g., bank accounts that can perform money transfers) and is independent of any UI. When using KO, you will usually make Ajax calls to some server-side code to read and write this stored model data.
A view model: a pure-code representation of the data and operations on a UI. For example, if you’re implementing a list editor, your view model would be an object holding a list of items, and exposing methods to add and remove items.
Note that this is not the UI itself: it doesn’t have any concept of buttons or display styles. It’s not the persisted data model either - it holds the unsaved data the user is working with. When using KO, your view models are pure JavaScript objects that hold no knowledge of HTML. Keeping the view model abstract in this way lets it stay simple, so you can manage more sophisticated behaviors without getting lost.
A view: a visible, interactive UI representing the state of the view model. It displays information from the view model, sends commands to the view model (e.g., when the user clicks buttons), and updates whenever the state of the view model changes.
When using KO, your view is simply your HTML document with declarative bindings to link it to the view model. Alternatively, you can use templates that generate HTML using data from your view model.
In addition to the answer already provided, there are a few things to keep in mind -
MVVM
Knockout is MVVM because it supports a good separation of concerns. Unlike other JavaScript libraries, such as jQuery, it's goal is to not pollute the view with that which does not concern it.
The view model's purpose is important to understand. It does not attempt to manipulate the DOM because only logic required to serve up data to the view is placed inside of it.
The view's purpose is only to present (render) the data. No logic, validation, or other logic code goes here.
The model is the only place where Knockout can get a bit tricky. It is generally a good accepted practice to place a separate model in your project for Knockout to use, but many developers have found the ease of mixing the model into the view model. The reason for this is obvious (some models are very basic) but again this is only out of ease of implementation.
MVC vs MV*
Surely there are other answers on SO.com that attempt to answer what is MV*, but I wanted to throw my $0.02 in here - Other libraries or frameworks speak to the fact that they are MVC or MVP or MV(whatever) based but Knockout is the only one that I have found that practices what it preaches in this regard. If you have the time and desire look at the structure of other frameworks such as Angular or Ember and you will see there is a blurred line that exists, and more or less they are simply using an MVVM based pattern but calling it something different.
Well I guess it can, however I am working on a project where all styling and UI layout manipulation is done in the knockout js ViewModel file, which is not good practice.

MVVM using constructors of UI to pass model

I'm over-thinking this and getting myself into a muddle but can't clear my head.
I'm new at WPF and I'm trying to get familiar with MVVM. I understand the theory. I need a view, a model and another model (called the view-model).
However, what happens if my model is constructed by a parameter of the View's constructor.
So, assuming I have a totally empty project, the only thing is I've an overloaded MainWindow constructor which takes the model:
public MainWindow(Logging.Logger logFile)
{
InitializeComponent();
this.DataContext = logFile;
}
The Model is the logFile. Can I still implement the MVVM when I don't have a separate Model class?
Any thoughts would be appreciated.
You're overthinking this.
There are several components to MVVM:
View:
The view provides a, well, view on the data. The view gets its data from a viewmodel
ViewModel:
The viewmodel is there to organise your data so that you can organise one or more sources of data into a coherent structure that can be viewed. The viewmodel may also perform basic validation. The ViewModel has no understanding of the UI so should not contain references to controls, Visibility, etc. A viewmodel gets its data from services.
Services:
Services provide data from external sources. These can be WCF, web services, MQ, etc (you get the idea). The data the service returns may need to be shaped so that it can be displayed in the UI. To do this you would take the raw data from the service and convert it to one or more Model objects.
Model:
A model object is an object that has been created so that it can be easily displayed/work with the UI.
You may find that you don't need to shape your data coming from your services (lucky you), in which case there's no need to create model objects. You may also decided that you don't want your services talking directly to your viewmodels but instead what to have them get their data via a "mediator" object. That's also good in some situations (usually when you're receiving a continuous stream of data from a source/multiple sources).
MVVM is a bit like porridge: there are lots of potential garnishes you can add, but you don't necessarily need to add them all. Or want to.
Does this help?
Edit: just stumbled on this: a more in-depth expression of what MVVM is:Mvvm Standardisation. This may also be useful
The Model is something the ViewModel will know about but not the View. If you need to present info about a Logger, you can certainly have a LoggerViewModel that knows about a Logger, and in turn the View winds up getting to know about the ViewModel. There are several ways to do that, and setting the DC in the view constructor is one of them.
After that basic understanding of who knows about who, what really makes the MVVM architecture pattern, IMO, is that ViewModel communicates to the View via databinding. Nothing more and nothing less. Lots of goodies come out of this, but that is the crux of it that makes it different than other separation of concerns patterns (like Presentation Model, MVP, etc)
That said, you need to get a feel for it by working through some sample projects. Asking questions here on SO is fantastic when you get stuck on something, but you must realize your question here is a bit fuzzy at best. Also, unless you are really looking to present logging info in your view, logging is not an MVVM concern. Its interesting alright but not MVVM.
Google Josh Smith's MVVM demo on MSDN for a perfectly meaty yet approachable beginning sort of project. And ask more questions or refine the one here as they come up!
HTH,
Berryl
forget the view! at least at the beginning ;)
try to think about what you want and what you need. what i understand is that you wanna handle a logfile. so you need a viewmodel for that.
public class LoggerViewmodel{}
you can put the logfile as a parameter to the vm ctor. now you have to think about what you wanna do with your logfile? for everything you want create a property (LastModified, LastRow, whatever) on your viewmodel.
btw there a two different ways to do mvvm, first is view first and the other is viewmodel first. i do both in my projects and take the appraoch wich fits better (viewmodel first the most time ;)) to my needs.
pls edit your questions and add what you wanna do with your logfile, then we can give you a better answer.
edit:
Can I still implement the MVVM when I don't have a separate Model class?
to answer your question the short way - yes you can. you have to seperate the view and viewmodel and use binding to bind the view to the datacontext(viewmodel).

ViewModel to ViewModel Communication

Given the following scenario:
ViewModelA launches ViewModelB (via a common Controller, of course, that uses Ioc and DI to resolve the types needed).
ViewModelB needs to set a property value in ViewModelA.
Is it bad to simply inject ViewModelA into ViewModelB via constructor injection and just set the property directly?
Or…
Should a messaging system like the EventAggregator from Prism be used to handle all communication between ViewModels?
I like the injection approach because it’s easy, but my instincts are telling me I’m missing something. I call on your collective wisdom to help fill in my blind spot.
I consider it a code smell if you need two-way references. Often you can replace one of the references with an event.
Let ViewModelB raise an event that ViewModelA subscribes to. A complete messaging system like the one found in Prism is certainly an option, but in your scenario it sounds like a 'normal' event will do just fine.
I suggest you read this question (and my answer) since it's similar, but not exactly your problem. It does deal with communication of properties between parent/child ViewModel objects.
Let's look at a basic example:
ViewModelA is the parent and has to present the Sum of some property on B
ViewModelB is the child and has a property that needs summing
So the user makes a request to edit the property on B and the request succeeds, so B presumably changes the value of its property and fires a PropertyChanged event.
ViewModelA could subscribe to the events on all children, but having gone down that path, I don't like it. When children are added and removed, you have a lot of bookkeeping to do.
Injecting A into B is cleaner, but you still have a lot of bookkeeping to do. What if you have a "Clear Children" action on A? You have to remember to properly get rid of the parent relationship from B to A in all cases. Still it's better than events in my opinion because it's more explicit.
Personally I like the messaging idea. I'm more familiar with MVVM Light's messenger than Prism, but it's the same idea... a global message bus. At any time, any B can say "I changed my property!" and then A listens for the notification and does the computation itself. I think this is your cleanest solution with much less bookkeeping.
I suggest using a much lighter dedicated Messaging solution called "Light Message Bus". It is not part of any yet another ;-) MVVM framework, but independent component. And I got it working in no time in less than 3 minutes.
You might find the sample applications of the WPF Application Framework (WAF) useful. The ViewModels don't know about each other. The mediation between them is done by Controllers. This way you can prevent cyclic dependencies between ViewModel objects.

Yet Another MVVM question... Is my understanding correct?

Sorry if this is a duplicate, It's not so much 'What is MVVM' though, but rather, 'Is this MVVM', I've read quite a bit, and think I've got a basic understanding of what it is, I've got my own 'one-liner', as such, on how I interpret it, but want to make sure it's correct before I firmly ingrain it in my head,
Essentially; The Model is pure data - no methods, there is one ViewModel per Model, it holds a reference to the Model - it performs all changes to the Models data and finally the View will hold one (or more) ViewModel reference(s) and format & display the data provided by the ViewModel.
(Not after links to tutorials, blogs etc, just a yes, or no with tweaks will be fine, as I'll have to re-read everything again anyway if not :) )
Not completely - at least, not as I would completely define it.
The Model does not have to be pure data. The model is the portion of your application that is completely domain specific, and has no "presentation related" information.
This will typically include all of the domain specific data, but also potentially methods that are pure business logic, and data access, etc. Anything specific to the business logic and processes, and not part of the "display", is part of the model.
Also, although "one ViewModel per Model" is the most common form of working, there are times when you may expose a "model" class through multiple ViewModels. This can be useful, for example, if you are trying to expose only part of a model to your designer, as it allows you to make a smaller ViewModel class. The ViewModel adapts the model for work with the View - if the entire Model is not required, this adapter can be made smaller (and more easily testable, maintainable, etc) by only working with the portion required.
Personally, I prefer to think in terms of "one ViewModel per View", as the ViewModel can adapt one or more models in order to work appropriately with a given View, but even then, sometimes it's helpful to swap out a ViewModel within the same View in order to change content.
Close, but not quite. Here are some points that are are different than yours:
Models can have methods on them. They are not just data. They might have methods like "retrieve", "store", etc. Business logic code. View agnostic.
There is no restriction to how many ViewModels hold a reference to the Model. ViewModels encapsulate view-level behavior, so you may have many different sets of behavior for the same model. For example, one ViewModel might be a read-only transformation of a model item. Another might provide read/write form validation on the same model item.
There can be more than one ViewModel per view, based on the behavior you want. For example, you might include "premium content" behavior with one ViewModel and "free content" behavior with another ViewModel but maintain the same view.
Essentially, yes. Practically, not really. Best practice is always to reduce dependencies and split up your responsibilities among classes on a 1:1 basis, but you'll find IRL situations where it isn't as easy to be a MVC purist.
I think the best attitude is to do your best, then document the rest. Don't sweat purity too much.
There is a lot of great information here, and I think that most of these answers are right. I don't think there is any 1 specific definition, nor is there 1 specific authority on this matter. Even microsoft does not really have clear definition on this.
The one item I would add which is not in the name of MVVM, but is common to all implementations of MVVM that I am familiar with. This is a Messaging or Notification system, which seems to always be linked as a platform for the ViewModel. Messaging just notifies the View Models when things change which may affect others. A good implementation of this in mind allows View Models and Views to both be agnostic about things they do not directly bind to by using generic notification messages.
The benefit of the entire pattern in my opinion is to make you application with modular, swappable parts with as little type-dependency as possible.
This is a real missing part in my mind, as it provides the same benefits / functions that you gain from separate controller logic in the MVC pattern.
That is pretty close. Except it is not correct to say that the Model is only pure data. It can and should contain methods for performing the various use cases against it.
Your understanding is wrong.
You can have several Models and all of them could have their own Views and then be a part of a single ViewModel.
Example:
You have the Models: Product, Customer
Each of them have their own View represented as a Custom Control
And you have a ViewModel which combines all your models and finally on the window of your app you combine all together your Views which talk to your Models via your ViewModel
Think of it like this. The Model is your system, the meat and veg of what the system does. The only considerations it has is how to do it's job, not how it is going to be used. It exposes events, attributes and methods defined at the system level, but it has no concept of what will be pressing it's buttons (or if it even has buttons!). It does not try to format data to a more user friendly format, it formats its data in a model friendly way.
The view model is the UX (user experience). It defines how you are going to use the system. It defines (through public commands and attributes) user orientated access into the system. It is the bridge that the user will use to enter the system. It binds onto the events of the model, and through it's commands, it will provide access into the models functionality.
It should handle validation, (is that age a sensible age?) retrieve data, converting and caching of records whilst they are being displayed. So, for example, you're looking at a patient record, the viewmodel gets the data from the model, and caches it internally, then publishes this to the view. What happens if the model announces an update to that data? Throw the cached data away? what if you've edited it? This is all up to you, and this behavior should be defined in the view model.
The view model is a "contract" of what functionality and data is exposed to the user (through the view). The view model has no concept of HOW it is going to be displayed or interacted with. Commands should be named at a functional level, such as RefreshList, NOT MouseClickHandler.
Finally, the View. This is simply a visible representation of what is in the view model. Buttons and menus etc bind onto commands. Fields bind onto attributes and will update automatically through the magic of binding.
If you ever see yourself doing : "text1.text = value" you're doing it wrong. If you ever find yourself writing a command handler that says "my.ViewModel.SomeCommand" you're doing it wrong.