set toastr.js options for each toast type individually

Sara Barrera Riano picture Sara Barrera Riano · Aug 25, 2017 · Viewed 12.6k times · Source

Is it possible to set toastr options for each toast type individually?

My toastr code

toastr.options = {
  "closeButton": true,
  "debug": false,
  "newestOnTop": false,
  "progressBar": false,
  "positionClass": "toast-bottom-right",
  "preventDuplicates": false,
  "onclick": null,
  "showDuration": "300",
  "hideDuration": "1000",
  "timeOut": "60000",
  "extendedTimeOut": "60000",
  "showEasing": "swing",
  "hideEasing": "linear",
  "showMethod": "fadeIn",
  "hideMethod": "fadeOut"
};

const infoMessage = $(".js-toast-message-info").html();
if (infoMessage && infoMessage.length > 0) {
  toastr.info(infoMessage);
}

const errorMessage = $(".js-toast-message-error").html();
if (errorMessage && errorMessage.length > 0) {
  toastr.error(errorMessage);
}

const warningMessage = $(".js-toast-message-warning").html();
if (warningMessage && warningMessage.length > 0) {
  toastr.warning(warningMessage);
}

const successMessage = $(".js-toast-message-success").html();
if (successMessage && successMessage.length > 0) {
  toastr.success(successMessage);
}

I already tried to put the different options types I want in the if statement of the specific toastr type, but with no result.

Is there an easy way to achieve this?

Answer

kbysiec picture kbysiec · Aug 25, 2017

You can create class e.g. Notifier which allows you to define different settings for specific message type.

Here is a simple solution:

toastr.options = {
  "closeButton": true,
  "debug": false,
  "newestOnTop": false,
  "progressBar": false,
  "positionClass": "toast-bottom-right",
  "preventDuplicates": false,
  "onclick": null,
  "showDuration": "300",
  "hideDuration": "1000",
  "timeOut": "60000",
  "extendedTimeOut": "60000",
  "showEasing": "swing",
  "hideEasing": "linear",
  "showMethod": "fadeIn",
  "hideMethod": "fadeOut"
};


class Notifier {
    constructor(opt) {
    this.dflt = {
        info: {
        "closeButton": false
      },
      success: {
        "progressBar": true
      },
      warning: {

      },
      error: {

      }
    }
    this.cfg = _.defaults(opt, this.dflt);
  }

  info(msg, tl, cfgOvr) {
    this.notify('info', msg, tl, cfgOvr);
  }

  success(msg, tl, cfgOvr) {
    this.notify('success', msg, tl, cfgOvr);
  }

  warning(msg, tl, cfgOvr) {
    this.notify('warning', msg, tl, cfgOvr);
  }

  error(msg, tl, cfgOvr) {
    this.notify('error', msg, tl, cfgOvr);
  }

  notify(lvl, msg, tl, cfgOvr) {
    let cfg = this.cfg[lvl];
    if (cfgOvr) {
      cfg = _.defaults(cfgOvr, cfg);
    }
    toastr[lvl](msg, tl, cfg);
  }
}

const notifier = new Notifier();
notifier.info('a', 'b');

What is good in the above, you can set your defaults, override them in constructor and additionally override for specific message usage.

working JSFiddle