Trying to show and hide a modal by calling new bootstrap.Modal() multiple times (potentially in different files) does not work. It seems you need to keep a reference to the returned object. In my opinion this should either be fixed or the documentation should be clearer in that case.
in JavaScript, new [blah] creates a new instance of an object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
i don't really think the bootstrap docs need to explain the basics of JavaScript
Then maybe implement it differently. With jquery you had the convenience to just call $(selector).modal('hide');
This is just an idea and it probably is not a good idea for some reasons and probably also not compatible and valid for some browsers. But what about something like this:
diff --git a/js/src/modal.js b/js/src/modal.js
index 9943f93e0..ece88f255 100644
--- a/js/src/modal.js
+++ b/js/src/modal.js
@@ -100,6 +100,13 @@ class Modal {
Data.setData(element, DATA_KEY, this)
}
+ static get(element, config) {
+ if (!element.modal) {
+ element.modal = new Modal(element, config)
+ }
+ return element.modal
+ }
+
// Getters
static get VERSION() {
Then you can just call:
bootstrap.Modal.get(selector).show()
Hi @mohe2015 it's already exist and documented.
You have to do:
var modal = bootstrap.Modal._getInstance(element)
modal.show()
modal.hide()
See: https://twbs-bootstrap.netlify.com/docs/4.3/components/modal/#getinstance
Oh thank you, that's nice. I just looked at the general javascript doc and missed that one.
You're welcome @mohe2015 馃槈
See a working example: https://codepen.io/Johann-S/pen/PrXJLJ
@Johann-S It seems to me that this would not initialize a modal if it wasn't already. What do you (and others) think about adding that for convenience? Or should I just clean up my code :laughing:
Yep _getInstance do not create a new instance but just return an existing one.
I'm not in favor of creating another helper method which do the same as a constructor.
/CC @twbs/js-review for other feedbacks
Most helpful comment
Hi @mohe2015 it's already exist and documented.
You have to do:
See: https://twbs-bootstrap.netlify.com/docs/4.3/components/modal/#getinstance