diff --git a/js/src/toast.js b/js/src/toast.js
index 9657048469..fd023e7021 100644
--- a/js/src/toast.js
+++ b/js/src/toast.js
@@ -82,7 +82,12 @@ class Toast {
// Public
show() {
- $(this._element).trigger(Event.SHOW)
+ const showEvent = $.Event(Event.SHOW)
+
+ $(this._element).trigger(showEvent)
+ if (showEvent.isDefaultPrevented()) {
+ return
+ }
if (this._config.animation) {
this._element.classList.add(ClassName.FADE)
@@ -119,7 +124,13 @@ class Toast {
return
}
- $(this._element).trigger(Event.HIDE)
+ const hideEvent = $.Event(Event.HIDE)
+
+ $(this._element).trigger(hideEvent)
+ if (hideEvent.isDefaultPrevented()) {
+ return
+ }
+
this._close()
}
diff --git a/js/tests/unit/toast.js b/js/tests/unit/toast.js
index 2081693ebc..3b5da05f3f 100644
--- a/js/tests/unit/toast.js
+++ b/js/tests/unit/toast.js
@@ -256,4 +256,75 @@ $(function () {
var toast = $toast.data('bs.toast')
assert.strictEqual(toast._config.delay, defaultDelay)
})
+
+ QUnit.test('should not trigger shown if show is prevented', function (assert) {
+ assert.expect(1)
+ var done = assert.async()
+
+ var toastHtml =
+ '
' +
+ '
' +
+ 'a simple toast' +
+ '
' +
+ '
'
+
+ var $toast = $(toastHtml)
+ .bootstrapToast()
+ .appendTo($('#qunit-fixture'))
+
+ var shownCalled = false
+ function assertDone() {
+ setTimeout(function () {
+ assert.strictEqual(shownCalled, false)
+ done()
+ }, 20)
+ }
+
+ $toast
+ .on('show.bs.toast', function (event) {
+ event.preventDefault()
+ assertDone()
+ })
+ .on('shown.bs.toast', function () {
+ shownCalled = true
+ })
+ .bootstrapToast('show')
+ })
+
+ QUnit.test('should not trigger hidden if hide is prevented', function (assert) {
+ assert.expect(1)
+ var done = assert.async()
+
+ var toastHtml =
+ '' +
+ '
' +
+ 'a simple toast' +
+ '
' +
+ '
'
+
+ var $toast = $(toastHtml)
+ .bootstrapToast()
+ .appendTo($('#qunit-fixture'))
+
+ var hiddenCalled = false
+ function assertDone() {
+ setTimeout(function () {
+ assert.strictEqual(hiddenCalled, false)
+ done()
+ }, 20)
+ }
+
+ $toast
+ .on('shown.bs.toast', function () {
+ $toast.bootstrapToast('hide')
+ })
+ .on('hide.bs.toast', function (event) {
+ event.preventDefault()
+ assertDone()
+ })
+ .on('hidden.bs.toast', function () {
+ hiddenCalled = true
+ })
+ .bootstrapToast('show')
+ })
})