未在自定义 OL3 控件的构造函数中定义的原型属性

Prototype property not defined inside a constructor of a custom OL3 control

本文关键字:定义 原型 属性 构造函数 自定义 OL3 控件      更新时间:2023-09-26

我正在尝试在 ol3 中创建自定义控件。我遇到了这个例子,并决定制作一些类,而不是在整个页面上编写一大堆代码。所以我有这样的东西:

var MeasureLength = function ( opt_options ) {
    var options = opt_options || {};
    var button = document.createElement( 'button' );
    button.innerText = 'M';
    button.addEventListener( 'click', this._trigger, false );
    var element = document.createElement( 'div' );
    element.className = 'measure-length ol-control';
    element.appendChild( button );
    ol.control.Control.call( this, {
        element: element,
        target: options.target
    } );
};
MeasureLength.prototype._trigger = function ( e ) {
    e.preventDefault();
    alert("Activating!");
};
ol.inherits( MeasureLength, ol.control.Control );

问题是没有调用_trigger。使其工作的一种方法是将_trigger放在构造函数中:

var _trigger = function ( e ) {
    e.preventDefault();
    alert("Activating!");
};
button.addEventListener( 'click', _trigger, false );

但我不喜欢这种方式,因为代码再次堆成一堆,所有 OOP 都崩溃了。

所以我的问题是:当您有大量代码时,在 ol3 中创建自定义控件的最佳实践是什么?

闭包的inherits函数用父级的实例覆盖子项的prototype

如果在调用 inherits 后附加 _triggered 属性,它应该在子构造函数中可用:

var MeasureLength = function ( opt_options ) {
    // should now be available
    console.log(this._trigger);
};
ol.inherits( MeasureLength, ol.control.Control );
MeasureLength.prototype._trigger = function ( e ) {
    e.preventDefault();
    console.log("Activating!");
};