0

I am using Bootrap 4 modal in vuejs which is called as:

> <a   href="#" class="" data-toggle="modal" :data-email="user.email" 
> data-target="#exampleModal">Delete</a>

I dynamically create onclick handler for a button in modal like:

mounted() {

    $('#exampleModal').on('show.bs.modal', function (event) {
      var button = $(event.relatedTarget) // Button that triggered the modal
      var email = button.data('email')
      var modal = $(this)
      modal.find('.modal-footer #delete').attr('onclick', "deleteUser('"+ email +"')")
    })

deleteUser is defined in methods section:

methods:
 deleteUser(email) {
  .....
}

As soon as I click Yes button in modal dialog, I get this error thrown:

Uncaught ReferenceError: deleteUser is not defined
    at HTMLButtonElement.onclick (users:1)
onclick @ users:1

How to solve this problem? I tried let $this = this and used $this.deleteUser but this does not work either.

The answers given in How to access the correct this inside a callback? are not related to vuejs and bootstrap 4 modal.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
ace
  • 11,526
  • 39
  • 113
  • 193
  • Normal functions define their own `this` context. See the linked duplicate to understand how to handle that in a callback. – Bert Jul 27 '18 at 13:23
  • `attr('onclick', "deleteUser('"+ email +"')")`, you put one string into the second parameter, and the first parameter should be `'onClick'`, so the final statement will be `attr('onclick', function () {$this.deleteUser( email))}`. or better way will be use `$('selector').click(function () {})` instead. – Sphinx Jul 27 '18 at 16:10
  • Use `modal.find('.modal-footer #delete').on('click', function(e){deleteUser(email)})`. Binding text to an `onclick` attribute will not create a [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures). The HTML can only access global scope. – georgeawg Jul 27 '18 at 16:57
  • @georgeawg when the user originally posted the question the original code was attempting to call `this.deleteUser` indicating the user was (and still is) attempting to call a method on the Vue. The problem then, and likely still is, that `this` is not pointing where he expects whether it was bound by jQuery or not. The ultimate solution to the problem will be to use an arrow function or closure or bind; whichever OP chooses. – Bert Jul 27 '18 at 17:09
  • Also, to be charitable, [here is working version](https://codepen.io/Kradek/pen/jpGJEx?editors=1010), with bootstrap 4. – Bert Jul 27 '18 at 17:21
  • I vote to [re-open the question](https://stackoverflow.com/review/reopen/20425282). It would be interesting to see if the OP accepts that answer. – georgeawg Jul 27 '18 at 17:35
  • 1
    @georgeawg and Sphinx comments are the answer to my question. Works great thank you. – ace Jul 27 '18 at 19:50

0 Answers0