Модификаторы L.DomUtil.get () не обновляют данные HTML - PullRequest
0 голосов
/ 12 декабря 2018

Создание карты с отображенными на ней маркерами.При нажатии на маркер, этот должен отображать всплывающее окно.Я расширил L.Popup следующим образом

L.InfrastructurePopup = L.Popup.extend({

    options: {
        template : "<form id='popup-form'>\
        <div>\
        <label for='problem'>Problem</label>\
        <textarea id='problem' rows='4' cols='46' placeholder='Type your text here'></textarea>\
        </div>\
        <div>\
        <label for='solution'>Solution</label>\
        <textarea id='solution' rows='4' cols='46' placeholder='Type your text here'></textarea>\
        </div>\
        <button id='button-submit' class='btn btn-primary' type='button'>Submit</button>\
        </form>",
    },

    setContent: function () {
        this._content = this.options.template;
        this.update();
        return this;
    },

    initializeForm(layer, callback)
    {
        var problem = L.DomUtil.get('problem');
        problem.textContent = layer.options.problem ? layer.options.problem : "";
        problem.addEventListener('change', (e) =>
        {
            layer.options.problem = problem.value;
        });
        var solution = L.DomUtil.get('solution');
        solution.textContent = layer.options.solution ? layer.options.solution : "";
        solution.addEventListener('change', (e) =>
        {
            layer.options.solution = solution.value;
        });

        var buttonSubmit = L.DomUtil.get('button-submit');
        buttonSubmit.addEventListener('click', (e) =>
        {
            callback(layer);
        });
    }
});

L.infrastructurePopup = function (options, source)
{
    return new L.InfrastructurePopup(options, source);
};

Я связал его с пользовательским маркером InfrastructureMarker, который имеет одно-единственное всплывающее окно, InfrastructurePopup.Поэтому, когда он вызывает функцию openPopup (), он загружает всплывающее окно на карту [map.addLayer (popup)] и дает мне правильные данные благодаря методу initializeForm (), который я вызываю после метода addLayer (popup).

L.Map.include({

    openInfrastructurePopup: function (layer, callback)
    {
        this.closePopup();

        layer._popup._isOpen = true;

        this.addLayer(layer._popup);

        layer._popup.initializeForm(layer, callback);
    }
});

L.InfrastructureMarker = L.Marker.extend({

    openPopup: function (callback)
    {
        if (this._popup && this._map && !this._map.hasLayer(this._popup))
        {
            this._popup.setLatLng(this._latlng);
            this._map.openInfrastructurePopup(this, callback);
        }

        return this;
    },
    togglePopup: function (callback)
    {
        if (this._popup)
        {
            if (this._popup._isOpen)
            {
                this._popup._isOpen = false;
                this.closePopup();
            }
            else
            {
                this.openPopup(callback);
            }
        }
        return this;
    },
    bindPopup: function (callback, options)
    {
        var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);

        anchor = anchor.add(L.Popup.prototype.options.offset);

        if (options && options.offset)
        {
            anchor = anchor.add(options.offset);
        }

        options = L.extend({offset: anchor}, options);

        if (!this._popupHandlersAdded)
        {
            this
                .on('click', () =>  {this.togglePopup(callback)}, this)
                .on('remove', this.closePopup, this)
                .on('move', this._movePopup, this);
            this._popupHandlersAdded = true;
        }

        this._popup = new L.infrastructurePopup(options, this).setContent();

        return this;
    },
});

L.infrastructureMarker = function (latlng, options)
{
    return new L.InfrastructureMarker(latlng, options);
};

Но если я решу щелкнуть один маркер, затем другой, не закрывая первый, он загрузит шаблон, но initializeForm (обратный вызов) не изменит данные.Я проверил все данные, чтобы узнать, пусто ли это или что-то, но все работало, я абсолютно не знаю, в чем проблема.Я полагаю, что всплывающее окно еще не установлено в DOM до моего запуска L.DomUtils.get, но я не должен видеть неопределенные элементы в console.log, когда я их получаю.

1 Ответ

0 голосов
/ 12 декабря 2018

Я действительно обнаружил, что происходит:

На самом деле, когда L.map вызывает свою функцию closePopup, он уничтожает слой.Поэтому после этого он создает новый для отображения.НО оставшийся HTML из предыдущего вида все еще существует.

Итак, я наконец-то связал одинаковые идентификаторы с двумя тегами HTML.Ересь!

Мое решение стало следующим:

    L.InfrastructurePopup = L.Popup.extend({

    setContent: function (layer)
    {
        var template = "<form id='popup-form'>\
        <div>\
        <label for='problem'>Problème Identifié</label>\
        <textarea id='" + layer._leaflet_id + "-problem' rows='4' cols='46' placeholder='Type your text here'></textarea>\
        </div>\
        <div>\
        <label for='solution'>Solution Proposée</label>\
        <textarea id='" + layer._leaflet_id + "-solution' rows='4' cols='46' placeholder='Type your text here'></textarea>\
        </div>\
        <button id='" + layer._leaflet_id + "-button-submit' class='btn btn-primary' type='button'>Submit</button>\
        </form>";

        this._content = template;
        this.update();
        return this;
    },
    initializeForm: function(layer, callback)
    {
        console.log(L.DomUtil.get(layer._leaflet_id+'-problem'));
        var problem = L.DomUtil.get(layer._leaflet_id + '-problem');
        problem.textContent = layer.options.problem ? layer.options.problem : "";
        problem.addEventListener('change', (e) =>
        {
            layer.options.problem = problem.value;
        });
        var solution = L.DomUtil.get(layer._leaflet_id + '-solution');
        solution.textContent = layer.options.solution ? layer.options.solution : "";
        solution.addEventListener('change', (e) =>
        {
            layer.options.solution = solution.value;
        });

        var buttonSubmit = L.DomUtil.get(layer._leaflet_id + '-button-submit');
        buttonSubmit.addEventListener('click', (e) =>
        {
            callback(layer);
        });
    }
});

L.infrastructurePopup = function (options, source)
{
    return new L.InfrastructurePopup(options, source);
};

Вызов setContent при создании моего InfrastructurePopup с layer_id и установке его в мой шаблон заставил его работать.

Я получил: '97-проблема 'или '99-проблема' и '97-решение 'или '99-решение

...