Handling pending sweet alerts

Author: kentmwCreated Oct 5, 2015Updated May 18, 2024

EDIT: Please look at my later comment for most recent SwalService and guidelines

I know this should be a pull request. But I wanted to add the wrapper I wrote here anyway so I can get feedback if this is a useful addition.

This usage here is that anywhere in your application you can call swalService.swal() and if there are open sweet alerts, it will queue them and put a notification on the current sweet alert that there is a pending alert. The swal method will return a unique identifier so you can call close on a specific sweet alert even if its is pending.

var _ = require('underscore');

var swalService = {
  pendingSwal: [],
  currentSwal: null,
  swalFirstCalled: false,
  __swal: require('sweetalert'),

  swal: function() {
    var pending = {
      args: arguments,
      id: _.uniqueId()
    }
    if (this.isSwalOpen()) {
        this.pendingSwal.push(pending);
    } else {
      this.__swal.apply(null, pending.args);
      this.currentSwal = pending;
      if (!this.swalFirstCalled) {
        $('.sweet-alert').prepend('<span class="other-messages"></span>');
        this.swalFirstCalled = true;
      }
    }
    this.refreshPendingText();
    return pending.id;
  },

  refreshPendingText: function() {
    if (_.isEmpty(this.pendingSwal)) {
      $('.other-messages').text('');
    } else {
      $('.other-messages').text(_.size(this.pendingSwal) + ' unread alerts');
    }
  },

  close: function(id) {
    if (_.isUndefined(id) || (this.currentSwal && this.currentSwal.id == id)) {
      this.__swal.close();
    } else if (!_.isUndefined(id) && !_.isEmpty(this.pendingSwal)) {
      var indexOfSwalToClose;
      for (var i = 0; i < this.pendingSwal.length; i++) {
        if (this.pendingSwal[i].id == id) {
          indexOfSwalToClose = i;
          break;
        }
      }
      if (!_.isUndefined(indexOfSwalToClose)) {
        this.pendingSwal.splice(indexOfSwalToClose, 1);
        this.refreshPendingText();
      }
    }
  },

  onCloseOfCurrentSwal: function() {
    swalService.currentSwal = null;
    if (_.size(swalService.pendingSwal) > 0) {
      var pending = swalService.pendingSwal.shift();
      swalService.swal.apply(swalService, pending.args);
    }
  },

  isSwalOpen: function() {
    return !_.isUndefined(this.currentSwal) && !_.isNull(this.currentSwal);
  },

  setSwalDefaults: function() {
    this.__swal.setDefaults({});
    var originalClose = this.__swal.close;
    this.__swal.close = function() {
      originalClose();
      setTimeout(_.bind(swalService.onCloseOfCurrentSwal, swalService), 400);
    };
  }

};