• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

ES6 rozdzielenie klasy na pare plików

Object Storage Arubacloud
0 głosów
163 wizyt
pytanie zadane 26 czerwca 2017 w JavaScript przez Sławek Obywatel (1,270 p.)

Cześć wszystkim! Mam takie pytanie, bo kiedyś utworzyłem inny post z oceną czystości kodu pewnego skryptu, użytkownik rafal612b prosił mnie gdy skończę żebym wrzucił poprawiony skrypt, więc teraz wrzucę, sory że tak późno ale jeszcze rozbudowywałem ten skrypt, i robiłem troche innych rzeczy już niezwiązanych z tym skryptem, poniżej ten skrypt wygląda teraz tak:

class Geolocations
{

    constructor(radius_circle,elements,WaitForDataFromDatabase,TableTypeSelectedIcon,TableIfIconSelect,markers_on_map,ifBounceMarkerIs) {
        this.radius_circle = radius_circle;
        this.elements=elements;
        this.WaitForDataFromDatabase=WaitForDataFromDatabase;
        this.TableTypeSelectedIcon=[TableTypeSelectedIcon];
        this.TableIfIconSelect=[TableIfIconSelect];
        this.markers_on_map=[markers_on_map];
        this.ifBounceMarkerIs=ifBounceMarkerIs;
    }

    init(options) {

      if(!options.location) 
      {
        return;
      }

      kind_checked(1);

      this.kind_travel=["RECOMMENDED","DRIVING","TRANSIT","WALKING","BICYCLING"];

      this.options = options;
      this.location = this.options.location;

      this.path = new google.maps.DirectionsService(),
      this.pathRender = new google.maps.DirectionsRenderer();

      this.initDOMElements();

      try {google.maps.event.addDomListener(window, "load", this.makeMap.bind(this)); } catch(e) { return; }

      try {google.maps.event.addDomListener(window, "load", this.listener.bind(this)); } catch(e) { return; }



    }
    initDOMElements()
    {
      this.animation = document.querySelector("#load-animation");
      this.list = document.querySelector(".lista");

      this.route = document.querySelector("#route");
      this.GPSlocation = document.querySelector("#location");
      this.set_the_route = document.querySelector("#set-the-route");

      this.begin_point = document.querySelector("#begin-point");
      this.end_point = document.querySelector("#end-point");

      this.time_pointer_travel = document.querySelector("#time-pointer-travel");

      this.title = document.querySelector("#title");
      this.street = document.querySelector("#street");
      this.phone = document.querySelector("#phone");
      this.monday = document.querySelector("#monday");
      this.tuesday = document.querySelector("#tuesday");
      this.wednesday = document.querySelector("#wednesday");
      this.thursday = document.querySelector("#thursday");
      this.friday = document.querySelector("#friday");
      this.saturday = document.querySelector("#saturday");
      this.about_location = document.querySelector("#about-location");
      this.about_ofert = document.querySelector("#about-ofert");
    }

    makeMap() {

        this.getAllLocations();

        var loc = this.location.split(","),
            pos = new google.maps.LatLng(loc[0], loc[1]);

        this.mapOptions =new google.maps.Map(document.querySelector("#map"), {
            zoom: 13,
            center: pos,
            disableDefaultUI: true,
            scaleControl: true,
            zoomControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            streetViewControl:true,
            mapTypeControl: true,
            mapTypeControlOptions:
            {
                position: google.maps.ControlPosition.BOTTOM_LEFT 
            }
        });

        this.Map=new google.maps.Map(document.getElementById("map"), this.mapOptions);

        if (navigator.geolocation) 
        {
          navigator.geolocation.getCurrentPosition((position)=> {

            this.myCoordsLatitude=position.coords.latitude;
            this.myCoordsLongitude=position.coords.longitude;
            this.myCoords=new google.maps.LatLng(this.myCoordsLatitude, this.myCoordsLongitude);

            var marker = new google.maps.Marker({
              map: this.Map,
              position: this.myCoords,
              animation: google.maps.Animation.BOUNCE,
              icon: "images/marker.png"
            });

            displayingNavLocation(2,200);

          });
        }

        this.createCircle();  

    }

    getAllLocations()
    { 
      this.animation.style.display="block";

      var lan="https://floating-lake-51759.herokuapp.com/api/connectAll/";

      this.sendRequestToDatabase(lan,undefined,this.animation);
    }

    listener(){    

      google.maps.event.addListener(this.Map,'dragstart',()=>{this.circle.setMap(null);});

      google.maps.event.addListener(this.Map,'dragend',this.createCircleonDragEnd.bind(this));

      google.maps.event.addListener(this.Map,'click',()=>{this.hideSlide();if(planTheRoute.style.display=='none'){displayingNav(0,0);}});

      this.GPSlocation.addEventListener("click", this.getGeoData.bind(this));

      this.route.addEventListener("click", this.drawRoute.bind(this));

      this.set_the_route.addEventListener("click", this.prepareRoute.bind(this));
    }

    createCircleonDragEnd()
    {
      this.cleanMarkersOnMap();

      this.createCircle();

      this.GeocodeLocations();

    }

    createCircle()
    {
      this.mylat=this.Map.getCenter().lat();

      this.mylng=this.Map.getCenter().lng(); 

      this.circle = new google.maps.Circle({
        map: this.Map,
        position: new google.maps.LatLng(this.mylat, this.mylng),
        radius: this.radius_circle,    
        strokeColor: '#b2dae8',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        clickable: false,
        fillColor: '#b2dae8',
        fillOpacity: 0.35
      });

      this.circle.bindTo('center', this.circle, 'position');
    }

    GeocodeLocations()
    {
      for (var iteration = 0; iteration < this.BringDataFromDatabase.locations.length; iteration++) {

        this.saveGlobalLocationsValueInClass(this.BringDataFromDatabase.locations[iteration],iteration);

      }
    }

    saveGlobalLocationsValueInClass(LocationsOnMap,iteration)
    {
      this.LocationsOnMap=LocationsOnMap;
      this.iteration=iteration;
      this.setMarkerLocation(iteration)
    }

    setMarkerLocation()
    {

      var wartosc=this.computeDistance();
      var marker_lat_lng=wartosc[0];
      var distance_from_location=wartosc[1];

      if (distance_from_location <= this.radius_circle) {

        this.new_marker=this.creatNewMarker(marker_lat_lng);

        this.filtersMarkers();

        this.infoWindows(marker_lat_lng);

        this.markers_on_map.push(this.new_marker);

      }
      
    }

    filtersMarkers()
    {

      if(this.CheckLocationsTypeOrName())
      {

        this.new_marker.setVisible(true); 

      }
      else
      {
        this.new_marker.setVisible(false);
      }      

      this.filtersMarkersOnTypeSelectedIcon();
                          
    }

    CheckLocationsTypeOrName()
    {
      if(this.BringDataFromDatabase.locations[this.iteration].type.indexOf(this.address) != -1
        || this.BringDataFromDatabase.locations[this.iteration].name.indexOf(this.address) != -1
        ||this.BringDataFromDatabase.locations[this.iteration].name==this.address 
        || this.BringDataFromDatabase.locations[this.iteration].type==this.address)
      {

        return true; 

      }
      else
      {
        return false; 
      }      
    }

    zoomMarker()
    {
      var infoWindowLocations=this.LocationsOnMap;

      var getPositionMarker=this.new_marker;

      google.maps.event.addListener(this.new_marker, 'click', ()=> {

        if(planTheRoute.style.display=='block')
        {
          displayingRoute('none');
        }
        this.pathRender.setMap(null);
        this.pathRender.setPanel(null);
        this.Map.panTo(getPositionMarker.getPosition());
        this.Map.setZoom(17);
        displayingNav(4,400);
        this.hideSlide();
        this.checkIsBounceMarker();

        this.getInformationAboutLocation(infoWindowLocations);
      });  
    }

    hideSlide(){

      if(this.list.style.display == "block")
      {
        $(this.list).slideToggle("fast");
      }
    }

    getInformationAboutLocation(infoWindowLocations)
    {
      this.clickedMarker=infoWindowLocations.name;

      this.latMarker=infoWindowLocations.lat;

      this.lngMarker=infoWindowLocations.lng;

      this.title.textContent=infoWindowLocations.name;
      this.street.textContent=infoWindowLocations.street;
      this.phone.textContent=infoWindowLocations.phone;
      this.monday.textContent=infoWindowLocations.data_open.monday;
      this.tuesday.textContent=infoWindowLocations.data_open.tuesday;
      this.wednesday.textContent=infoWindowLocations.data_open.wednesday;
      this.thursday.textContent=infoWindowLocations.data_open.thursday;
      this.friday.textContent=infoWindowLocations.data_open.friday;
      this.saturday.textContent=infoWindowLocations.data_open.saturday;
      this.about_location.textContent=infoWindowLocations.information;
      this.about_ofert.textContent=infoWindowLocations.oferts;

      this.coordsEndPoint=this.latMarker+","+this.lngMarker;

    }

    getGeoData(){

      this.Map.panTo(this.myCoords);
      this.Map.setZoom(17);

    }

    drawRoute()
    {
      this.geocoder = new google.maps.Geocoder();
      this.geocoder.geocode({'location': this.myCoords}, (results, status)=>{this.gecode(results, status)});

      this.anotherLocation=google.maps.event.addListener(this.Map,'click',(event)=>{this.anotherStartLocation(event)});
    }

    checkIsBounceMarker()
    {
      if(this.ifBounceMarkerIs)
      {
        this.clicked_marker_bounce.setMap(null);
        this.latitude=0;
        this.longitude=0;
        this.ifBounceMarkerIs=false;
      }  
    }

    anotherStartLocation(event)
    { 

      this.checkIsBounceMarker();

       this.latitude = event.latLng.lat();
       this.longitude = event.latLng.lng();
       this.coordsClickedPoint=new google.maps.LatLng(this.latitude, this.longitude);

       this.clicked_marker_bounce = new google.maps.Marker({
        map: this.Map,
        position: this.coordsClickedPoint,
        animation: google.maps.Animation.BOUNCE,
      });

       this.ifBounceMarkerIs=true;

       this.geocoder.geocode({'location': this.coordsClickedPoint}, (results, status)=>{this.gecode(results, status)});
    }

    gecode(results, status)
    {
      if (status === 'OK') {
        if (results[1]) {

          this.myLocation=results[1].formatted_address;
          this.begin_point.value=this.myLocation;
        }
      }
    }

    prepareRoute()
    { 

      var renderOptions = {
          map: this.Map,
          polylineOptions: {
            strokeColor: "#ff0000",
            strokeWeight: 4,
            strokeOpacity: 0.8
          },
          suppressMarkers: true
      }

      this.pathRender.setOptions(renderOptions);
      this.pathRender.setPanel(this.time_pointer_travel);

      var pathData = {
        origin: this.setBeginPosition(),
        destination: this.coordsEndPoint,
        travelMode: google.maps.TravelMode[this.kind_travel[number_travel_mode]]
      };

      this.path.route(pathData, this.handleRoute.bind(this));
    }

    setBeginPosition()
    {
      if(this.begin_point.value!==this.myLocation){
        this.checkIsBounceMarker();
        return this.begin_point.value;
      }
      else if(this.begin_point.value===this.myLocation && this.coordsClickedPoint!==undefined && this.latitude!==0){
        return this.coordsClickedPoint;

      }
      else{
        return this.myCoords;
      }
    }

    handleRoute(result, status) {

      if(status != google.maps.DirectionsStatus.OK || !result.routes[0]) {
        alert("Wprowadziłeś złe dane!");
        return false;
      }

      this.pathRender.setDirections(result);
      this.clickedMarker = result.routes[0].legs[0].start_address;
        
    }
    
    sendRequestToDatabase(lan,val,animation)
    {
      var saveLocationsFromDatabaseArrowFunction=(BringDataFromDatabase)=>this.BringDataFromDatabase=BringDataFromDatabase;
      var displayLocations=(val)=>this.updateAddressValue(val);

      var xhr = new XMLHttpRequest();
      
      xhr.open("GET",lan,true);

      xhr.onreadystatechange = function(e)
      {

        if (this.readyState === 4 && this.status === 200) {
          
          var res=this.response;
          var BringDataFromDatabase=JSON.parse(res); 

          saveLocationsFromDatabaseArrowFunction(BringDataFromDatabase);

          if(val!== undefined)
          {
            displayLocations(val);
            
          }
          animation.style.display="none";
     
        }
      };

      xhr.send(null);
    }

}

 

Jak pewnie zauważyliście, pojawił się kolejny problem ten skrypt rozrósł się tak, że ciężko się po nim poruszać,było jeszcze więcej funkcji ale nie mogłem wstawić tyle znaków w tym poście, szukałem rozwiązania w googlach, i jedyny sensowny sposób jaki udało mi się znależć to dziedziczenie, a wiem że dziedziczenie w javascript inaczej wygląda niź w normalnym języku obiektowym np C# więc prosiłbym o jakieś tutoriale jeśli znajdziecie na temat dziedziczenia w javascript, i prosiłbym o jakieś rady czy jest jakiś inny sposób na rozdzielenie tej klasy niż dziedziczenie.

P.S Prosiłbym też o rady na temat poprawienia czystości kodu tego skryptu, bo na pewno można jeszcze coś poprawić:)

1 odpowiedź

0 głosów
odpowiedź 26 czerwca 2017 przez Comandeer Guru (601,450 p.)

Dziedziczenie to najgorsze rozwiązanie tutaj. Poczytaj sobie o kompozycji oraz o SOLID i podziel te klasy na mniejsze. Bo tak na oko można by to spokojnie podzielić na co najmniej 3-4 mniejsze klasy.

Podobne pytania

0 głosów
2 odpowiedzi 254 wizyt
pytanie zadane 24 listopada 2017 w JavaScript przez goran. Użytkownik (930 p.)
+1 głos
1 odpowiedź 362 wizyt
pytanie zadane 29 listopada 2017 w JavaScript przez UltraSF Stary wyjadacz (11,740 p.)
0 głosów
2 odpowiedzi 158 wizyt
pytanie zadane 23 czerwca 2017 w JavaScript przez niezalogowany

92,575 zapytań

141,424 odpowiedzi

319,649 komentarzy

61,961 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj.

Akademia Sekuraka

Kolejna edycja największej imprezy hakerskiej w Polsce, czyli Mega Sekurak Hacking Party odbędzie się już 20 maja 2024r. Z tej okazji mamy dla Was kod: pasjamshp - jeżeli wpiszecie go w koszyku, to wówczas otrzymacie 40% zniżki na bilet w wersji standard!

Więcej informacji na temat imprezy znajdziecie tutaj. Dziękujemy ekipie Sekuraka za taką fajną zniżkę dla wszystkich Pasjonatów!

Akademia Sekuraka

Niedawno wystartował dodruk tej świetnej, rozchwytywanej książki (około 940 stron). Mamy dla Was kod: pasja (wpiszcie go w koszyku), dzięki któremu otrzymujemy 10% zniżki - dziękujemy zaprzyjaźnionej ekipie Sekuraka za taki bonus dla Pasjonatów! Książka to pierwszy tom z serii o ITsec, który łagodnie wprowadzi w świat bezpieczeństwa IT każdą osobę - warto, polecamy!

...