Why does bootstrap-datepicker trigger 'show.bs.modal' when it is displayed?

这一生的挚爱 提交于 2019-12-03 07:36:43

问题


I have a modal, illustrated below,

When I select the input field that contains the date picker, the bootstrap modal event .on('show.bs.modal') gets triggered, which is super problematic because I'm taking all kinds of async action when the modal is legitimately shown. I'm of the opinion that the modal is already shown and this event should not be firing.

I have a listener on the bootstrap event 'show.bs.modal' as referenced below,

  handleModalLaunch: () ->
    $(@modalClass).on 'show.bs.modal', (event) =>
      return if event.dates
      promise = new Promise ( (resolve, reject) =>
        @setModalData(event)
        if (@interactionData)
          resolve(@interactionData)
        else
          reject(false)
      )
      promise.then(
        (results) =>
          @trigger 'setRooms', @callBacks
          @trigger 'setStudentInfo', @callBacks
        (err) ->
          err
      )

And effectively, the listener is being triggered again which is subsequently calling the promise and associated callbacks, the triggering of the event is problematic because of course, the modal is already show and I don't want these callbacks/promise being run.

I added return if event.dates (event.dates being a property unique to the datepicker event), to basically short circuit this code in the event that the date-picker triggered the modal show event, but of course, this is hacky and I'd like to better understand why the datepicker itself is triggering the show event. Potentially, since my show even listener is tied to the class of the modal, the act of showing the datepicker probably inherits the target of the parent modal and is likely itself a modal, ie, the modal(datepicker) is shown and since the datepicker inherits from the parent modal, the event triggers as though it was the parent modal being 'shown'. Have I utterly confused this? (Actually, it seems clearer to me now, but still need to understand how to fix.)


回答1:


This is a bug in date picker library. You can track it on github here. There is workaround given there by @kroeder

$("#my-datepicker").datepicker().on('show.bs.modal', function(event) {
    // prevent datepicker from firing bootstrap modal "show.bs.modal"
    event.stopPropagation(); 
});



回答2:


Use this

$(date-picker-selector).on("show", function(e){
     e.preventDefault();
     e.stopPropagation();
}).on("hide", function(e){
     e.preventDefault();
     e.stopPropagation();
});



回答3:


Try this:

modal.on('show.bs.modal', function(e) {
    if (e.namespace === 'bs.modal') {
        // Your code here
    }
});


来源:https://stackoverflow.com/questions/30113228/why-does-bootstrap-datepicker-trigger-show-bs-modal-when-it-is-displayed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!