传单JS面向对象的最佳方法

LeafletJS best approach to object oriented

本文关键字:方法 最佳 面向对象的 JS 传单      更新时间:2023-11-24

我正在用传单js做一个小项目,我想知道什么是实现OOP的最佳方法。好的,交易是这样的:

创建一个使用标记的"类",这些标记来自数据库。所以,我想我会创建一个对象数组,我说得对吗

我的第一个问题是,我必须创建一个自定义类,将标记对象作为该类的属性,还是从传单中扩展L.marker类?

第二个问题:如何在每个标记上绑定点击事件,这样这个事件就可以调用和ajax请求,并绑定一个带有信息的弹出窗口。

到目前为止,这是我的代码:

<script>
    var map = L.map('map').setView([25.55246, -103.50328], 18);
    var marcas = [];
   L.tileLayer('https://{s}.tiles.mapbox.com/v3/kinopio.kikc39gj/{z}/{x}/{y}.png', {
        maxZoom: 18
    }).addTo(map);
    function Marcador(marca, usuario, seccional, identificador){
        this.marca = marca;
        this.identificador = identificador;
        this.usuario = usuario;
        this.seccional = seccional;
    }
    Marcador.prototype.verUsuario = function(){
        console.log(this.usuario);
    }
    Marcador.prototype.verVotos = function(){
        $.ajax({
            type: 'GET',
            url: '/votos/' + this.identificador,
            datatype: 'json',
            success:function(data){
                msg = $.parseJSON(data);
                //marcador.bindPopup('Votos: ' + msg[0].Votos ).openPopup();
                console.log(msg[0].Votos);
            }
        });
    }
    function onMapClick(e) {
//When clicking in the map, create a marker so i can register a new one to the DB...
        var formulario =    "<form action='/registro' id='registro' method='post'> " +
                                "<input name='usuario' placeholder='usuario'> " +
                                "<input name='password' placeholder='passwword'>" +
                                "<input name='seccional' placeholder='seccional'>" +
                                "<input name='latitud' type='hidden' value = " + e.latlng.lat  + ">" +
                                "<input name='longitud' type='hidden' value = " + e.latlng.lng + ">" +
                                "<input type='submit' value='Aceptar'>" +
                            "</form>"
        var marker = L.marker( e.latlng ).addTo( map ).bindPopup( formulario );
            marker.on("popupopen", function(){
               
                var forma = $('#registro');
                forma.on('submit', function(ev){
                    ev.preventDefault();
                    $.ajax({
                        type: forma.attr('method'),
                        url: forma.attr('action'),
                        data: forma.serialize(),
                        success:function(data){
                            marker.closePopup();
                            marker.bindPopup( 'Usuario registrado exitosament' ).openPopup();
                        }
                    });
                });
            });
        }
        function cargarRegistros(e){
            e.preventDefault();
            $.ajax({
                type: 'GET',
                url: '/registrados',
                datatype: 'json',
                success: function(d){
                    $.each(d.marcadores, function(i, item){                        
                        marca = new L.marker( [ parseFloat(item.latitud), parseFloat( item.longitud) ] )
                                    .addTo(map).bindPopup();
                        marcas.push( new Marcador( marca, item.usuario, item.seccional, item.identificador ) );
                    });
                }
            });
            return marcas;
        }
        map.on('click', onMapClick);
        function clickMarcador(e){
            console.log(e.target  + '---' + e.currentTarget);
            if (e.target.id !== e.currentTarget) {
                console.log('hola');
            }
            
            e.stopPropagation();
    }
    $('#registrados').on('click', cargarRegistros);
</script>

我只想扩展L.Marker类以包括所需的功能,例如,点击事件,当标记的onAdd方法被触发时,你可以挂起它,并在onRemove方法上取消挂起它:下面是一个代码示例(使用来自jQuery的$.getJSON):

L.CustomMarker = L.Marker.extend({
  onAdd: function (map) {
    this.on('click', this.clickHandler);
    L.Marker.prototype.onAdd.call(this, map);
  },
  onRemove: function (map) {
    this.off('click', this.clickHandler);
    L.Marker.prototype.onRemove.call(this, map);
  },
  clickHandler: function (e) {
    $.getJSON('data.json', function (data) {
      e.target.bindPopup(data.myProperty);
      e.target.openPopup();
    }, this);
  }
});
L.customMarker = function (latLng, options) {
  return new L.CustomMarker(latLng, options);
} 

以下是Plunker的一个工作示例:http://plnkr.co/edit/hNlvhC?p=preview

当然,这是非常粗糙的,在实际实现中,如果弹出窗口已经绑定,则会检查click事件,这样您就不会绑定它两次,但它可以让您很好地了解扩展L.Marker 的可能性

关于存储标记,您可以只使用L.LayerGroup和对地图的那个。创建标记时,您需要将其添加到组中。这样,您就可以使用层组的实用程序方法,如hasLayergetLayerclearLayerseachLayer等。

以下是L.LayerGroup的参考:http://leafletjs.com/reference.html#layergroup