Basically, I wanted to add a few custom methods to google.maps.Map and Rectangle classes. I could not do it, so I decided to make wrapper cl开发者_Go百科asses, but I ran into one problem
function MyClass() {
this.redraw_map = function() {draw something};
this.current_map = new google.maps.Map();
google.maps.event.addListener(this.current_map, 'bounds_changed', function() {
redraw_map();
});
}
My redraw_map() method is not seen in the event handling function, unless I put the redraw method outside MyClass. I have in plans to switch to more advanced way writing JS apps like Backbone, but first I need to understand how to overcome such problems.
Thanks for reading.
This happens because the callback function that you're passing to addListener does not have a function defined redraw_map() in its current scope. A workaround is to keep a reference to your MyClass scope outside of your callback, allowing you to call it from inside the callback.
This will fix your problem:
function MyClass() {
this.redraw_map = function() {draw something};
this.current_map = new google.maps.Map();
// Reference to current scope
var self = this;
google.maps.event.addListener(this.current_map, 'bounds_changed', function() {
// This will call the function that you defined in your scope above
self.redraw_map();
});
}
精彩评论