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

import/export w javascript

Object Storage Arubacloud
+1 głos
383 wizyt
pytanie zadane 3 sierpnia 2021 w JavaScript przez xjafajx Użytkownik (740 p.)

Cześć,

Co mogę zrobić jeżeli js mam rozbitego na dwa pliki i do jednego z tych plików potrzebuje zawartość zmiennych z drugiego pliku.

Dla zrozumienia plik script.js zawiera poniższy kod

var element = document.getElementById('mobile_control');
var hammertime = new Hammer(element);


hammertime.get('swipe').set({ direction: Hammer.DIRECTION_ALL });
hammertime.on('swipeleft', function(ev) {
  cmove("prev");
});
hammertime.on('swiperight', function(ev) {
  cmove("next");
});

$(".action").on("click", function(){
  cmove($(this).attr('id'));
});

var angle = 0;
var planet_id = 0;
showSlide(0);

function cmove(dir){
  const n_planet = planets.length;
  var next_id;
  var prev, next;
  var top = $("#pl"+ planet_id);
  var orbit = $(".planet_container");
  
  top.removeClass("pt");
  
  if(planet_id == 0){
    prev = $("#pl"+ (n_planet-1));
    next = $("#pl"+ (planet_id+1)%n_planet);
  }else{
    prev = $("#pl"+ (planet_id-1));
    next = $("#pl"+ (planet_id+1)%n_planet);
  }
  
  if(dir == "prev"){
    next_id = ++planet_id % n_planet;
    angle -= 45;
    prev.addClass("pt");
    if(planet_id > 7) next_id = planet_id = 0;
  }else if(dir == "next"){
    next_id = --planet_id % n_planet;
    angle += 45;
    next.addClass("pt");
    if(planet_id < 0) next_id = planet_id = 7;
  }else{
    next_id = planet_id = 0
  }

  if (typeof planet[next_id] !== 'undefined') {
    $('.pn').each(function(){
      $(this).html(planet[next_id].replace( "<span class='letter'>$&</span>"));
      console.log(next_id);
    });
  }

  anime.timeline({})
  .add({
    targets: '.pn .letter',
    translateX: [40,0],
    translateZ: 0,
    opacity: [0,1],
    easing: "easeOutExpo",
    duration: 1200,
    delay: function(el, i) {
      return 500 + 30 * i;
    }
  });
  
  orbit.css("transform", "rotateZ(" + angle + "deg)");
  

}
const  planet_to_polish =  ["Strona główna", "Strona 7", "Strona 6","Strona 5", "Strona 4", "Strona 3", "Strona 2", "Strona 1"],
const planet_to_english =  ["Home page", "Page 7", "Page 6","Page 5", "Page 4", "Page 3", "Page 2", "Page 1"];
 
var planet = [...planet_to_polish]; 


const planets = document.querySelectorAll('.moon');

let moon_id = 0;
moon();

function moon(direction = null){
  const n_planet = planets.length;
  let moon_next;

  if(direction == "prev"){
    moon_next = ++moon_id % n_planet;
    if(moon_id > 7) moon_next = moon_id = 0;
  }else if(direction == "next"){
    moon_next = --moon_id % n_planet;
    if(moon_id < 0) moon_next = moon_id = 7;
  }else{
    moon_next = moon_id = 0;
  }

  showSlide(moon_next);
  planets.forEach( (planet) => { planet.style.visibility = 'hidden'; });  
  planets[moon_next].style.visibility = 'visible';
}

function showSlide(id){
  const slides = ['index', 'seventh', 'sixth', 'fifth', 'fourth', 'three', 'second', 'first'];
  slides.forEach( (slide) => {
    $("#" + slide).css("opacity", 0);
    $("#" + slide).css("display", "none");
  });  
  $("#" + slides[id]).css("opacity", 1);
  $("#" + slides[id]).css("display", "block");

};

 

Natomiast plik language.js zawiera poniższy kod:

const translate_to_english = [
    null,
    'Home',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'first',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'second',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'three',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'fourth',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'fifth',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'sixth',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'seventh',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'Home',
    'First page',
    'Second page',
    'Three page',
    'Fourth page',
    'Fifth page',
    'Sixth page',
    'Seventh page',
];

const translate_to_polish = [
    null,
    'Główna',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'pierwsza',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'druga',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'trzecia',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'czwarta',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'piąta',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'szósta',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'siódma',
    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    'Strona Główna',
    'Strona pierwsza',
    'Strona druga',
    'Strona trzecia',
    'Strona czwarta',
    'Strona piąta',
    'Strona szósta',
    'Strona siódma',
];

const button_translate = document.querySelectorAll('[data-translate-switch]');

button_translate.forEach((button) => {
  button.addEventListener('click', (e) => {
    e.preventDefault();
    switch(e.target.id) {
      case "english": planet = [...planet_to_english];
                      insertTranslate(translate_to_english);
        break;
      case "polish": planet = [...planet_to_polish];
                     insertTranslate(translate_to_polish);
        break;
                
    }
  
    function insertTranslate(translate) {
      const content_to_translate = document.querySelectorAll('[data-translate-id]');

      content_to_translate[0].textContent = planet[moon_id];
      content_to_translate.forEach((tag_html, index) => {
         if (index > 0) tag_html.innerHTML = translate[index];
      });
    }
  });
});

 

Aby plik language.js funkcjonował poprawnie to potrzebuje z pliku script.js zaciągnąć następującą zawartość czyli zmienną moon_id, tablicę planet, tablicę planet_to_polish oraz tablicę planet_to_english.

Jak to najlepiej połączyć żeby dobrze funkcjonowało? Czy ktoś może mi pomóc i doradzić?

Z góry dziękuję za wszelką pomoc

komentarz 4 sierpnia 2021 przez VBService Ekspert (253,340 p.)

Polecam lekturę Moduły i Export and Import

komentarz 4 sierpnia 2021 przez xjafajx Użytkownik (740 p.)

@VBService ok udało się ale nie wiem dlaczego wyświetla mi że funkcja moon przy onclick jest niezdefiniowana jeżeli w script.js występuje :(

1 odpowiedź

0 głosów
odpowiedź 3 sierpnia 2021 przez ScriptyChris Mędrzec (190,190 p.)

W najprostszej formie, użyj export dla zmiennych, które chcesz opublikować z danego modułu i import tam, gdzie chcesz ich użyć. Czyli w pliku script.js na końcu zapisz:

export {
  moon_id,
  planet,
  planet_to_polish,
  planet_to_english,
}

W pliku language.js na początku zapisz:

import {
  moon_id,
  planet,
  planet_to_polish,
  planet_to_english,
} from 'path/to/script.js'

W razie komplikacji pokaż strukturę tych plików (ich wzajemną relację w projekcie) i ewentualne komunikaty błędów.

komentarz 3 sierpnia 2021 przez xjafajx Użytkownik (740 p.)
a jak wskazać tą strukturę plików (wzajemną relację w projekcie) i ewentualne błędy?
komentarz 3 sierpnia 2021 przez ScriptyChris Mędrzec (190,190 p.)
Struktura jest pokazana w IDE (program, w którym programujesz) lub nawet w systemowym eksploratorze plików, a ewentualne błędy albo w konsoli przeglądarki albo w konsoli IDE podczas kompilacji.
komentarz 3 sierpnia 2021 przez xjafajx Użytkownik (740 p.)
Ok w razie jakiś problemów będę wrzucał to co mi konsola przeglądarki wywala (komunikaty o błędach)
komentarz 3 sierpnia 2021 przez Wiciorny Ekspert (269,810 p.)

@ScriptyChris,  jak się do tego ma programowanie funkcyjne, czy stan obiektów jest przekazywany skoro JS np działa synchronicznie? 
Jeśli tak, to jak to się ma do side - effektów, czy monad? 

komentarz 3 sierpnia 2021 przez xjafajx Użytkownik (740 p.)

@ScriptyChris pojawiły się takie błędy

Zablokowano żądanie do zasobu innego pochodzenia: zasady „Same Origin Policy” nie pozwalają wczytywać zdalnych zasobów z „file:///C:/Users/jafaj/Desktop/site/js/script.js” (żądanie CORS inne niż HTTP).

Zablokowano żądanie do zasobu innego pochodzenia: zasady „Same Origin Policy” nie pozwalają wczytywać zdalnych zasobów z „file:///C:/Users/jafaj/Desktop/site/js/language.js” (żądanie CORS inne niż HTTP).

 

 

 

komentarz 3 sierpnia 2021 przez Wiciorny Ekspert (269,810 p.)
w swojej aplikacji jeśli kożystasz z różnych url musisz zaimplementować politykę CORS, zezwolić/ lub ograniczyć dowolność zapytań, bo domyślenie zapytania o róznych endpointach będą blokowane z odp. z serwera. Po stronie serwera powinieneś zewzolić na cors, miej na uwadzę że port jest istotny jak i protokuł http/http , domena także
komentarz 3 sierpnia 2021 przez xjafajx Użytkownik (740 p.)

@Wiciorny jak to zrobić bo pierwszy raz się z czymś takim spotykam?

komentarz 3 sierpnia 2021 przez Wiciorny Ekspert (269,810 p.)
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
zależy czy operujesz tylko w oparciu o warstwe klienta, czy dzielisz to na klient-server

poczytaj tutaj, dobre jest tłumaczenie
Druga sprawwa to pewnie fakt : Próbujesz załadować plik z lokalnego dysku, a przeglądarka ci nie pozwala.https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp tu jest sylabus

Podobne pytania

0 głosów
0 odpowiedzi 129 wizyt
0 głosów
1 odpowiedź 97 wizyt
pytanie zadane 2 lutego 2019 w PHP przez Piotr Szramowski Użytkownik (860 p.)
0 głosów
0 odpowiedzi 1,212 wizyt

92,568 zapytań

141,424 odpowiedzi

319,634 komentarzy

61,956 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!

...