2012-06-06 52 views
2

我目前正在創建一個包含OpenLayers組件(地圖本身)的應用程序原型。創建一個繼承自「OpenLayers.Feature.Vector」的JavaScript類

我想創建特殊的「功能」,這將有其他屬性。

它們應該從繼承OpenLayers.Feature.Vector,也就是說,使用它的自定義參數和附加屬性的構造函數。

我一直在尋找,但我找不到任何簡單的例子。

*注意:我的應用程序對象結構不是基於「OpenLayers.Class」類型,因此它們是常見的javascript對象。

所以這裏是一個應該從OpenLayers.Feature.Vector繼承和應該返回它的一個特例類,

// Class "SpecialRegion" 
function SpecialRegion(bounds, options) { 

/* should return an OpenLayers.Feature.Vector with additional properties (objects) which makes this class different */ 

} 

在此先感謝。

回答

2

如果你想擴展OpenLayers.Feature.Vector類,我強烈建議,你將不得不使用OpenLayers.Class對象:

SpecialRegion = OpenLayers.Class(OpenLayers.Feature.Vector, { 
    customAttribute: 'value', 

    /** 
    * OpenLayers Constructor 
    */ 
    initialize: function(bounds, options) { 
     // Call the super constructor, you will have to define the variables geometry, attributes and style 
     OpenLayers.Feature.Vector.prototype.initialize.apply(this, {geometry, attributes, style}); 
     this.customAttribute = 'new value'; 
    }, 

    // Each instance will share this method. It's clean and efficient 
    customMethod: function(param) { 
     ... 
    } 
}); 

實例化

var myVector = new SpecialRegion(bounds, options); 
myVector.customMethod(param); 
var val = myVector.customAttribute; 

如果您只想爲單個實例定義特殊的方法和/或屬性,而不必定義它自己的類:

注意:如果您執行此操作,您的應用程序可能會變得非常混亂太常見了,我會建議上面的解決方案。

function customMethod2 = function(param) { 
    ... 
}; 

function SpecialRegion(bounds, options) { 
    // Call the constructor, you will have to define the variables geometry, attributes and style 
    var vector = new OpenLayers.Feature.Vector(geometry, attributes, style); 

    vector.customAttribute = 'new value'; 

    // Each instance created with SpecialRegion will have their own copy of this method, the code is cleaner but it's memory inefficient 
    vector.customMethod = function(param) { 
     ... 
    }; 

    // Each instance share the same copy of this method (defined on top), the code is harder to read/maintain but it's more memory efficient 
    vector.customMethod2 = customMethod2; 

    return vector; 
}; 

實例化

var myVector = SpecialRegion(bounds, options); 
// Don't use the keyword 'new' here, SpecialRegion is a function, not a proper class. 
myVector.customMethod(param); 
myVector.customMethod2(param); 
var val = myVector.customAttribute;