【问题标题】:Prototype property not defined inside a constructor of a custom OL3 control未在自定义 OL3 控件的构造函数中定义原型属性
【发布时间】:2016-02-09 15:26:17
【问题描述】:

我正在尝试在 ol3 中创建自定义控件。我遇到了this example,并决定创建一些类,而不是在页面上堆满一大堆代码。所以我有类似的东西:

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的顺序和trigger的定义吗? IIRC,闭包在使用inherits时替换了子原型。

标签: javascript openlayers-3 google-closure


【解决方案1】:

Closure 的 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!");
};

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 2011-10-30
    • 1970-01-01
    • 2018-01-14
    相关资源
    最近更新 更多