I have the function below.
Everything works fine except for the Push
, Pop
and Remove
method. These method should be called by the event-handler. This event is fired by the Google Maps API.
The problem is that when the event is fired, these method are not found. I have a “Push is not defined” error message.
I tried with this but that’s not working.
How do I call the public method from the event handler?
function Track(mapContainer) { var map = mapContainer; var points = new Array(); var isEditMode = false; var clickListener; this.Push = function(point) { ... } this.Pop = function() { ... } this.Remove = function(point) { ... } //Enable / disable the marker placements this.PlaceWaypoint = function(isPlacing) { if (isPlacing != true) { if (clickListener != null) { google.maps.event.removeListener(clickListener); clickListener = null; } } else { clickListener = map.AddEvent("click", function(event) { if (!IsDoubleClick()) { var point = map.PlaceMarker(new WayPoint(event.latLng)) point.RemoveListener(function() { Remove(point); }); Push(point); } else { Pop(); } }); } } }
Advertisement
Answer
You’ve got a closure/binding problem. One convention that is frequently used it to assign a variable called self of that, which can later be used in place of this, thanks to the closure properties of JS.
function Track(mapContainer) { var map = mapContainer, points = new Array(), isEditMode = false, clickListener, // Make a variable self that points to this, that can be used inside closures // where the original context is lost self = this; this.Push = function(point) { ... } this.Pop = function() { ... } this.Remove = function(point) { ... } //Enable / disable the marker placements this.PlaceWaypoint = function(isPlacing) { if (isPlacing != true) { if (clickListener != null) { google.maps.event.removeListener(clickListener); clickListener = null; } } else { clickListener = map.AddEvent("click", function(event) { if (!IsDoubleClick()) { var point = map.PlaceMarker(new WayPoint(event.latLng)) point.RemoveListener(function() { Remove(point); }); // Use the closure reference self instead of this self.Push(point); } else { // Use the closure reference self instead of this self.Pop(); } }); }; }