This project has moved. For the latest updates, please go here.

NotificationManager

NotificationManager offers a simple way to handle broadcast messages within your application. A common case of this is handing login/logout events.

Like DataManager, NotificationManager is accessed via a singleton Current property, as follows:

NotificationManager.Current.RaiseMessage(LoginMessage, lm);                        

Receiving Messages

Registering for receiving a message is done with a call to:

 

NotificationManager.Current.RegisterForMessage(LoginMessage, (message, value) => {MessageBox.Show("Got message " + value.ToString()) );

 

Where LoginMessage is just a string identifying the message name, and a handler to be invoked when the message is raised.

Sending Messages

Sending messages is also easy.  Following along with the above example:

 

NotificationManager.Current.RaiseMessage(LoginMessage, "shawn");                        

 

Unregistering for Messages

NotificationManager currently holds a strong reference to the handlers that it gets via RegisterForMessage. These handlers may hold your object in memory (this is something I need to look into), so be sure that you unregister your handlers when you don't need the notification anymore, as in this sample code:

 

public partial class MainPage : PhoneApplicationPage {

        private Action loginHandler;

        public MainPage() {
            InitializeComponent();

            loginHandler = (key, data) =>
            {

                if (LoginModel.Current.IsLoggedIn) {
                    this.DataContext = DataManager.Current.Load(LoginModel.Current.UserId);
                }

            };

        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
            NotificationManager.Current.RegisterForMessage(LoginMessage, loginHandler);

            loginHandler(LoginMessage, null);

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) {
            NotificationManager.Current.UnregisterForMessage(LoginMessage, loginHandler); base.OnNavigatedFrom(e);
        }
    }

Last edited Mar 31, 2011 at 12:36 AM by shawnburke, version 7

Comments

No comments yet.