简体   繁体   中英

set toastr options globally using javascript

I have a set of scripts that all use toastr. They look a bit like this:

import $ from 'jquery';
import toastr from 'toastr';
import list from './data/address';
import { selectedApp, validate, getCookie, setCookie } from './common';

$(document).ready(function () {
    toastr.options = {
        'closeButton': true,
        'debug': true,
        'newestOnTop': false,
        'progressBar': true,
        'positionClass': 'toast-top-full-width',
        'preventDuplicates': false,
        'onclick': null,
        'showDuration': '6000',
        'hideDuration': '1000',
        'timeOut': '50000',
        'extendedTimeOut': '1000',
        'showEasing': 'swing',
        'hideEasing': 'linear',
        'showMethod': 'fadeIn',
        'hideMethod': 'fadeOut'
    };

    // ---  Application code --- //
});

I have a few scripts and they all have the toastr.options declared at the top. Is there a way (perhaps using an import) that will allow me to set the toastr options globally?

If you want to use es6 modules, then you can create a separate toastr configuration. For instance,

import toastr from "toastr";

toastr.options = {
  closeButton: true,
  debug: true,
  newestOnTop: false,
  progressBar: true,
  positionClass: "toast-top-full-width",
  preventDuplicates: false,
  onclick: null,
  showDuration: "6000",
  hideDuration: "1000",
  timeOut: "50000",
  extendedTimeOut: "1000",
  showEasing: "swing",
  hideEasing: "linear",
  showMethod: "fadeIn",
  hideMethod: "fadeOut"
};

export default toastr;

Then simply importing this file at the top instead of toastr since this configures toastr and export the configured toastr . As

import toastr from './PathToAboveFile';

Or if you want an es5 style global configuration use,

window.toastrOptions = {...}

in a seperate js file and reference in each html page. Then in $(document).ready function you can set it.

toastr.options = window.toastrOptions;

Since now toastr options are in a separate file, it can be centrally configured.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM