问题
I want to make a specialized type of polygon object that wraps around or inherits from the google.maps.Polygon class. I want it to have a custom edited event that can be listened to, ideally via the normal addListener interface. Can this be done?
回答1:
I like JustinY's answer.
An alternative would be manually triggering an event like this:
function CustomPolygon(options) {
var self = this;
// initialize any options
console.log('init')
}
function edit() {
// do work!!!
// now tell people about it!
google.maps.event.trigger(this, 'edited');
}
// extend CustomPolygon from google.maps.Polygon
CustomPolygon.prototype = new google.maps.Polygon();
CustomPolygon.prototype.edit = edit;
// now you can do
var p = new CustomPolygon({ /*options*/
});
google.maps.event.addListener(p, 'edited', function () {
document.body.innerHTML = 'edited!';
});
p.edit();
See http://jsfiddle.net/stevejansen/hQZcT/
Source: https://developers.google.com/maps/documentation/javascript/reference#event
回答2:
In a Google Developers article titled Fun with MVC we find two ways to do this.
In the Binding Properties section we learn that whenever the
set(property, value)method is called on anMVCObject, a magicproperty_changedfunction is called (if present).// Prints "something changed to ftw!!!" myObject.something_changed = function(){ console.log('something changed to ' + this.get('something')); } myObject.set('something', 'ftw!!!');In the Outputting Information section we learn of that the less mystical
addListener()method can also be used for listening to changes in values withset(). The following code snippet does the exact same thing as the code above.// Prints "something changed to ftw!!!" myObject.addListener('something_changed', function(){ console.log('something changed to ' + this.get('something')); } myObject.set('something', 'ftw!!!');
I prefer method #2 because it involves less black magic.
来源:https://stackoverflow.com/questions/21321157/how-can-i-create-custom-events-for-google-maps-api-v3-objects