How can I create custom events for google maps api v3 objects?

心不动则不痛 提交于 2019-12-21 06:09:54

问题


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.

  1. In the Binding Properties section we learn that whenever the set(property, value) method is called on an MVCObject, a magic property_changed function 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!!!');
    
  2. In the Outputting Information section we learn of that the less mystical addListener() method can also be used for listening to changes in values with set(). 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

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