JS Kodundaki Sorun Nedir?

Can Deger

Centipat
Katılım
27 Mart 2023
Mesajlar
64
Daha fazla  
Cinsiyet
Erkek
Evet sevgili uyeler, oncelikle herkese cani gonulden bir selam veriyorum. Yuzdum yuzdum sonuna geldim ama su an icin JS ile alakali problemlerim var. JS'te bana anlatip ogretecek hoca da ariyorum ama su an icin kendim ittirmeye calisiyorum. Gecen bir problemi sag olsun bir uye sayesinde cozdum ona da selam olsun, sag olsun var olsun. Simdi ki durum soyle: Ben rezerve_pixel kismina selectedneighbor listesini attim. Simdi ikinci kisim var, check_pixel_status'e bu veriyi atmak istiyorum ama `Null` donuyor. JS gercekten benlik bir yapi degil ama zarla zorla ogreniyorum.
JavaScript:
// Global olarak tanımlanan bir değişken
var selectedNeighborNumbers = [];

var reserve = {
  // (B) SAVE RESERVATION
  save: function() {
    // (B1) GET SELECTED PIXEL
    var selected = document.querySelector(".selected");

    // (B2) ERROR!
    if (selected == null) {
      alert("No pixel selected.");
    } else {
      // (B3) SELECTED PIXEL NUMBER
      var pixelValue = selected.textContent.trim();
      var extractedValue = pixelValue.match(/\d+/);
      var pixelID = extractedValue ? extractedValue[0] : null;

      if (pixelID !== null) {
        // (B3-1) SEND TO SERVER
        var data = new FormData();
        data.append("pixel_id", pixelID);
        data.append("selected_neighbors", selectedNeighborNumbers.join(',')); // Listeyi virgüllerle birleştirip gönderiyoruz
        console.log("Selected Neighbors:", JSON.stringify(selectedNeighborNumbers));
        data.append("KEY", "VALUE"); // add more data as required

        fetch("/reserve_pixel", {
          method: "POST",
          body: data
        })
          .then(function(res) {
            return res.text();
          })
          .then(function(txt) {
            alert(txt); // Show error message as an alert
            // Store the updated pixel status in localStorage
            localStorage.setItem("pixel_" + pixelID, "dolu");
          })
          .catch(function(error) {
            console.log("An error occurred:", error); // Log the error message to the console
          });
      }
    }
  },
  toggle: function(pixel) {
    var pixelValue = pixel.textContent.trim();
    console.log(pixelValue);

    // Burada selectedNeighborNumbers değişkenini kullanabilirsiniz.
    console.log("Selected Neighbors in Toggle:", JSON.stringify(selectedNeighborNumbers));
   
    fetch("/check_pixel_status?pixel_id=" + pixelValue + "&selected_neighbors=" + selectedNeighborNumbers.join(','))
      .then(function(res) {
        return res.json();
      })
      .then(function(data) {
        console.log("Response BYRAUSIASI DATA:", data);
        if (data.reserved_status === "Dolu") {
          alert("This pixel is already taken.");
          pixel.classList.add("dolu");
          // Store the updated pixel status in localStorage
          localStorage.setItem("pixel_" + pixelValue, "dolu");
        } else {
          var selected = document.querySelectorAll(".selected");
          for (var i = 0; i < selected.length; i++) {
            selected[i].classList.remove("selected");
            selected[i].classList.remove("dolu");
          }
          pixel.classList.add("selected");
          // Remove the pixel status from localStorage if it is empty
          localStorage.removeItem("pixel_" + pixelValue);
        }
      })
      .catch(function(error) {
        console.log("Error:", error);
      });
  }
};
 
Null dönüyorsa bir yerde null atıyorsundur. Bu kodda herhangi bir atama göremedim. Doldurduğun yerleri de atarsan oralara da bakalım.
Hocam doldurdugum yerler HTML sayfasindan gelen click ile oluyor diye tahmin ediyorum. Global variable olarak verdim. Tam olarak nereyi atmam gerektigini anlamadim. Bir de surasi var ama bir bakarsaniz sevinirim.
JavaScript:
document.addEventListener("DOMContentLoaded", function() {
  var pixels = document.querySelectorAll('.pixel');

  pixels.forEach(function(pixel) {
    pixel.addEventListener('click', function() {
      var selectedPixelIndex = Array.from(pixels).indexOf(pixel);
      var numRows = 32; // Change this to the number of rows in your grid

      var selectedRow = Math.floor(selectedPixelIndex / numRows);
      var selectedCol = selectedPixelIndex % numRows;

      var selectedNeighbors = [];

      for (var rowOffset = 0; rowOffset < 2; rowOffset++) {
        for (var colOffset = 0; colOffset < 2; colOffset++) {
          var neighborRow = selectedRow + rowOffset;
          var neighborCol = selectedCol + colOffset;
          
          // Check if the neighbor is within grid bounds
          if (neighborRow >= 0 && neighborRow < numRows && neighborCol >= 0 && neighborCol < numRows) {
            var neighborIndex = neighborRow * numRows + neighborCol;
            var neighborPixel = pixels[neighborIndex];
            selectedNeighbors.push(neighborPixel);
          }
        }
      }

      // Highlight selected pixel and its neighbors
      pixels.forEach(function(p) {
        p.style.backgroundColor = '';
      });
      selectedNeighbors.forEach(function(n) {
        n.style.backgroundColor = 'yellow';
      });

      // Get the numbers of the selected neighbors
      var selectedNeighborNumbers = selectedNeighbors.map(function(neighbor) {
        return neighbor.querySelector('.pixel-number').textContent;
      });
      console.log("Selected Neighbor Numbers:", selectedNeighborNumbers);


      // Check if all selected neighbors are reserved
      var allReserved = selectedNeighborNumbers.every(function(neighborNumber) {
        var neighborPixel = document.querySelector('.pixel[data-pixel="' + neighborNumber + '"]');
        return neighborPixel && neighborPixel.classList.contains("dolu");
      });

      // Color selected neighbors accordingly
      if (allReserved) {
        selectedNeighbors.forEach(function(n) {
          n.style.backgroundColor = 'blue';
        });
      }
    });
  });
});
 
Code review lerde bile bu kadar kod incelemedim :D
Şaka bir yana, bu şekilde debug yapmak zor dostum. Çalışan bir prototipi online bir site üzerinden (örn; codesandbox, playcode.io, jsfiddle vs) paylaşırsanız daha iyi olur. Veya GitHub da mevcutsa repo linki de atabilirsin.
 

Technopat Haberler

Yeni konular

Geri
Yukarı