Google Maps Places Autocomplete - Uncaught TypeError: Cannot read property 'getPlace' of undefined

北城余情 提交于 2019-12-06 04:48:05

Inside the place_changed-callback the keyword this points to the object which has been triggered the event.

so you may simply use

var place = this.getPlace();

instead of

var place = this.destinationAutocomplete.getPlace();

How to keep the context/this of the controller?

tldr:

Create a function that returns a function with the context:

this.searchBox.addListener('places_changed', ((that) => () => this.placesChanged(that))(this));

Explanation

Like Dr.Molle points out: this points to the object which has triggered the event, namely the element on which you want to add an event listener on.

The addListener takes a function declaration. To keep access on your controller's this, you could also create a closure that passes the controller's this into the function, like so:

this.searchBox.addListener('places_changed', ((that) => () => this.placesChanged(that))(this));

Here I defined a function that takes a parameter called that, and upon execution returns a function that contains the this. It is a closure because the inner function's scope keeps a reference to the that variable from the outer functions scope (and other variables that could get passed to this.placesChanged).

Now if a event places_changed is emitted, the function declaration is ran. I am still able to change properties on the that variable inside the this.placesChanged function. This is possible because in objects are passed by reference (whereas primitive types are passed by values).

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