Return function value from a nested on click function

How can I get the success instead of undefined when openModal is called?

function deleteImg(model, name, id) {
  return 'success';
}
  
function openModal(model, name, id){
  $('#button').show();
  $('#button').on('click', function() {
//   console.log( deleteImg(model, name, id) );
     return deleteImg(model, name, id);
  })
}

console.log(openModal(1,2,3));
#button {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">
Button
</button>

I have also tried using $.when().done();

function openModal(model, name, id){
    var status;
    $.when(
      $('#button').show(),
      $('#button').on('click', function() {
//      console.log( deleteImg(model, name, id) );
        status = deleteImg(model, name, id);
      })
    ).done(
      function(){
        return status;
      }
    )
}

Thanks

1 answer

  • answered 2018-05-16 05:42 styopdev

    You can use callback pattern, just pass a function as a callback and call it from click listener.

    function deleteImg(model, name, id) {
      return 'success';
    }
    
    function openModal(model, name, id, cb){
      $('#button').show();
      $('#button').on('click', function() {
         // return deleteImg(model, name, id);
         cb(deleteImg(model, name, id));
      })
    }
    
    openModal(1,2,3, function (res) {
        console.log(res);
    });