Publish an Event without PayLoad in Prism EventAggregator?

后端 未结 2 835
北海茫月
北海茫月 2021-02-19 20:47

Why can\'t we Publish Events without any PayLoad.

    _eventAggregator.GetEvent().Publish(new SelectFolderEventCriteria() { });
         


        
2条回答
  •  一向
    一向 (楼主)
    2021-02-19 21:30

    Good question, I don't see a reason for not publishing an event without a payload. There are cases where the fact that an event has been raised is all information you need and want to handle.

    There are two options: As it is open source, you can take the Prism source and extract a CompositePresentation event that doesn't take a payload.

    I wouldn't do that, but handle Prism as a 3rd party library and leave it as it is. It is good practice to write a Facade for a 3rd party library to fit it into your project, in this case for CompositePresentationEvent. This could look something like this:

    public class EmptyPresentationEvent : EventBase
    {
        /// 
        /// Event which facade is for
        /// 
        private readonly CompositePresentationEvent _innerEvent;
    
        /// 
        /// Dictionary which maps parameterless actions to wrapped 
        /// actions which take the ignored parameter 
        /// 
        private readonly Dictionary> _subscriberActions;
    
        public EmptyPresentationEvent()
        {
            _innerEvent = new CompositePresentationEvent();
            _subscriberActions = new Dictionary>();
        }
    
        public void Publish()
        {
            _innerEvent.Publish(null);
        }
    
        public void Subscribe(Action action)
        {
            Action wrappedAction = o => action();
            _subscriberActions.Add(action, wrappedAction);
            _innerEvent.Subscribe(wrappedAction);
        }
    
        public void Unsubscribe(Action action)
        {
            if (!_subscriberActions.ContainsKey(action)) return;
            var wrappedActionToUnsubscribe = _subscriberActions[action];
            _innerEvent.Unsubscribe(wrappedActionToUnsubscribe);
            _subscriberActions.Remove(action);
        }
    }
    
    
    

    If anything is unclear, please ask.

    提交回复
    热议问题