为每个toast类型单独设置toastr.js选项

时间:2017-08-25 08:39:40

标签: jquery toastr

是否可以单独为每个Toast类型设置toastr选项?

我的代码

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);
}

我已经尝试将我想要的不同选项类型放在特定toastr类型的if语句中,但是没有结果。

有没有简单的方法来实现这一目标?

2 个答案:

答案 0 :(得分:3)

您可以创建课程,例如通知程序,允许您为特定的消息类型定义不同的设置。

这是一个简单的解决方案:

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');

上面有什么好处,您可以设置默认值,在构造函数中覆盖它们,并另外覆盖特定的消息用法。

working JSFiddle

答案 1 :(得分:0)

您可以像这样将配置选项作为第三个参数传递

toastr.warning('Please Allow Pop-ups for multiple selection','Popup Blocked',{
    "timeOut": 0,
    "extendedTimeOut": 0,
    "preventDuplicates": true,
    "disableTimeOut" : true,
});

这不会覆盖您的全局配置

相关问题