I'm working on a view model for a view that presents a dialog with export options. The user selects options then clicks Export. When the view model completes the Export, the calling view model receives notification.
I'm curious which is the better practice for implementing the notification: a traditional event or an Action
callback that gets passed in when the dialog is opened.
Traditional Event
public class ExportDialogViewModel : ViewModelBase
{
private readonly ICommand _exportCommand;
private readonly ICommand _cancelCommand;
public event EventHandler Finished;
public ICommand ExportCommand
{
get { return _exportCommand; }
}
public ICommand CancelCommand
{
get { return _cancelCommand; }
}
public ExportDialogViewModel()
{
_exportCommand = new RelayCommand(Export);
_cancelCommand = new RelayCommand(Cancel);
}
public void Initialize()
{
//set the initial conditions
}
public void Export()
{
//perform export
OnFinished();
}
public void Cancel()
{
OnFinished();
}
private void OnFinished()
{
if (Finished != null) Finished(this, EventArgs.Empty);
}
}
Callback
public class ExportDialogViewModel2 : ViewModelBase
{
private readonly ICommand _exportCommand;
private readonly ICommand _cancelCommand;
private Action _callback;
public ICommand ExportCommand
{
get { return _exportCommand; }
}
public ICommand CancelCommand
{
get { return _cancelCommand; }
}
public ExportDialogViewModel2()
{
_exportCommand = new RelayCommand(Export);
_cancelCommand = new RelayCommand(Cancel);
}
public void Initialize(Action callback)
{
_callback = callback;
//set the initial conditions
}
public void Export()
{
//perform export
_callback();
}
public void Cancel()
{
_callback();
}
}
My initial thoughts are that the traditional event is a little more flexible: it allows more than one subscriber to be notified, and it also allows zero subscribers to be notified. The callback, on the other hand, enforces a particular way of interacting with the dialog--the callback must be passed in during initialization. The callback is also simpler to implement and use, though perhaps less familiar than events.
Which of the two notification patterns do you recommend and why?