Observer pattern using jQuery.Callbacks

Let's see an example of the observer pattern using the jQuery.Callbacks function.

To start with, let's add two functions which can help to understand the following flags that can be used with jQuery.Callbacks:

function newsAlert(notification) {
  alert(notification);
}
 

function appAlert(notification) {
  alert( "In appAlert function: "+notification);
  return false;
}

Possible flags available for jQuery.callbacks are listed as follows:

  • once: It will make sure that callback is called only once.
        var messages = $.Callbacks( "once" );
        messages.add(newsAlert);
        messages.fire("First Notificaiton");
        messages.add(appAlert);
        messages.fire("Second Notification");

    Here, the output is First Notification.

    Whenever run for the first ...

Get Test-Driven JavaScript Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.