简体   繁体   中英

How can I extend google.maps.Map with coffeescript

I have tried standard way:

class MyMap extends google.maps.Map
  constructor: (mapDiv, opts)->
    super(mapDiv, opts)

But in this case placeholder was empty.

This problem is a combo of the way CoffeeScript makes classes and the way that the Google Maps Javascript API is written/obfuscated/minified.

When CoffeeScript extends a class, it creates code something similar to this:

customnamespace.CustomMap = (function(_super) {

    // '__extends' is a method that gets output at the 
    // top of every CoffeeScript compiled file
    __extends(CustomMap, _super);

    function CustomMap(mapDiv, opts) {
        CustomMap.__super__.constructor.apply(this, arguments);
    }

    return CustomMap;

})(google.maps.Map);

In most cases, and especially in cases where the "extendee" was written in CoffeeScript, this works great.

But in the case of google.map.Maps there is (I suspect) a whole bunch of scope manipulation going on and it's kindof undoing the scope CoffeeScript tries to set. Admittedly this is a guess.

So in this case it's time to put on ye olde JavaScript hat and just do some plain old scope-locking on the constructor. So drop your super and apply the function in the scope of the class with a line of JavaScript. CoffeeScript will just wave, smile, and output the JavaScript line as is.

class MyMap extends google.maps.Map
    constructor: (mapDiv, opts)->
        google.maps.Map.apply(this, [mapDiv, opts]);

Make sense?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM