Object function () {} does not have a "my method" method,

I am using the ( searchTransportation

) method to callback the event.

exports.searchTransportation = function (items, num, UrlS) {
//...
}

exports.doHotelInsertion = function(items, num, typetransport, UrlS, callback) {
  // (omitted code)


  event.on("STARTWITHAIRSEARCH" + num, searchTransportation ); //!!! causes error

};

      

I have tried something like

  event.on("STARTWITHAIRSEARCH" + num, this.searchTransportation(items, num,
          UrlS).bind(this));

      

But this is a code violation and ends with Object function () {} has no method 'searchTransportation'

I understand that the event callback is in the global scope, but is there a way to call an existing method?

- EDIT

it's a bit like this SO question: Class methods as event handlers in javascript , but with twist nodejs. What's the most elegant way to do this?

+3


source to share


2 answers


It happens that yours callback

gets called before your function event.on

calls this.searchTransportation.bind(...)

.

So you lose your valid that pointer as the function has already completed. this pointer no longer refers to a valid object (perhaps your object is out of scope and cleared from memory).

You have two options for solving this problem: The first is to create local variables that will persist until the end of the asynchronous call:

exports.doHotelInsertion = function(items, num, typetransport, UrlS, callback) {

  var _items = items;
  var _num = num;
  var _UrlS = UrlS; 
  var localthis = this;

  event.on("STARTWITHAIRSEARCH" + num, localthis.searchTransportation(_items, _num, _UrlS));
};

      



The second and more elegant thing would be to bind the variables as parameters to your asynchronous call so that they persist.

exports.doHotelInsertion = function(items, num, typetransport, UrlS, callback) {

  // somestuff
  var localthis = this;

  event.on("STARTWITHAIRSEARCH" + num, localthis.searchTransportation(items, num, UrlS));
};

      

You still need to create a local variable for this, but at least for others it will be neater.

+3


source


I'm guessing it searchTransportation

doesn't return a function, so your binding string should look like this:

event.on("STARTWITHAIRSEARCH" + num, this.searchTransportation.bind(this, items, num, UrlS));

      



MDN: fun.bind(thisArg\[, arg1\[, arg2\[, ...\]\]\])

+2


source







All Articles