Search code examples
javascriptjqueryes6-promise

How I get return value after trigger jquery?


I have custom event.

$('body').on('searchPlaceOnWebMap', (event, payload) =>
  this.webMap.getPlaces(payload).then(data => data)
);

I get google places in my getplaces promise function, this function return data for me. If I write .then(data => { console.log(data) }) I see result.

Then I try get data after trigger

const result = $('body').trigger('searchPlaceOnWebMap', searchValue)

But I can't do it.

How I can get return value after trigger?


Solution

  • You can't directly return a value from an event handler. You would need to pass your Promise using the event object. jQuery does this automatically by assigning the value to the result property of the event object:

    event.result

    Description: The last value returned by an event handler that was triggered by this event, unless the value was undefined.

    $('body').on('searchPlaceOnWebMap', (event, payload) => this.webMap.getPlaces(payload));
    

    That is equal to:

    $('body').on('searchPlaceOnWebMap', (event, payload) => {
      event.result = this.webMap.getPlaces(payload)
    });
    

    And to be able to access the returned Promise after your trigger, you need to create a custom event object that you pass to the trigger function:

    var e = jQuery.Event("searchPlaceOnWebMap");
    $('body').trigger(e, obj)
    
    //e.result now holds the promise
    e.result.then(value => {
      // do something with value
    })