gpt4 book ai didi

javascript - CoffeeScript 与其他库

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:38:09 24 4
gpt4 key购买 nike

我最近开始阅读有关 CoffeeScript 的文章 http://jashkenas.github.com/coffee-script/它看起来绝对惊人!但是我似乎无法弄清楚是否有一种简单的方法来访问/使用外部 JavaScript api。我广泛使用 OpenLayers,所以有人可以告诉我如何用 CoffeeScript 编写以下代码片段吗?

var map = new OpenLayers.Map('map_div', {
controls: [
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.LayerSwitcher({'ascending':false})
],
numZoomLevels: 6
});

最佳答案

需要注意的一个小问题是 OpenLayers 中的对象系统使用一个名为 initialize() 的函数作为构造函数,因此为了在扩展 OpenLayers 类时让 CoffeeScript 的 super 关键字正确工作,您需要装饰他们。我为此使用以下函数:

window.CompatibleClass = (cls) ->
class Wrapped
constructor: ->
# Call the OpenLayers-style constructor.
cls::initialize.apply @, arguments

# Copy prototype elements from OpenLayers class.
Wrapped::[name] = el for name, el of cls::

Wrapped

现在您可以像这样扩展 OL 内置:

class MySpecialFeature extends (CompatibleClass OpenLayers.Feature.Vector)
constructor: ->
super new OpenLayers.Geometry.Point 0, 0

CLASS_NAME: "MySpecialFeature"

编辑:澄清一下,像这样包装类的两种替代方法是按原样使用 OpenLayers 类系统,并错过 CoffeeScript 的一些语法优势,或者在每个类中手动调用初始化函数构造函数,感觉更脆弱,并围绕依赖项展开,而不是将其集中在单个装饰器中。

在 CoffeeScript 中按原样使用 OpenLayers 类系统:

MySpecialFeature = OpenLayers.Class OpenLayers.Feature.Vector,
initialize: ->
# Call super using apply, as is convention in OpenLayers
OpenLayers.Feature::initialize.apply @, new OpenLayers.Geometry.Point 0, 0
...
...

或者,使用 CoffeeScript 类,但扩展未修饰的 OpenLayers 类:

class MySpecialFeature extends OpenLayers.Feature.Vector
constructor: ->
# Call inherited initialize().
@initialize.apply @, new OpenLayers.Geometry.Point 0, 0
...
...

对于 OpenLayers 或 CoffeeScript 的其他开发人员而言,这些方法都不是惯用的或可识别的。我坚持我对包装器的建议,它允许在调用 OpenLayers 构造函数时使用 native super()。

关于javascript - CoffeeScript 与其他库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6969856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com