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

question-closed Problem z IIFE

Object Storage Arubacloud
0 głosów
194 wizyt
pytanie zadane 2 lutego 2017 w JavaScript przez Alex.Ironside Stary wyjadacz (14,900 p.)
zamknięte 6 lutego 2017 przez Alex.Ironside

Witam. Problem polega na tym ze kazda z funkcji takich jak clock() i changeSlide() dzialaja bez problemu poza iife, lecz juz zakmniete w tymze iife wywala blad. Jak to rozwiazac? Ponadto w contact nie dziala event.preventDefault().

JS

// CREATED BY ALEXANDER IRONSIDE FILE:app.js WEBSITE:http://ironalex.azurewebsites.net/
// iife = Immediately Invoked Function Expression
let doEverything = (function() {
    // number of picture for slider
    var number = 1;
    console.log(document.title);
    switch (document.title) {
        case "Alex Ironside - Home":
            document.addEventListener("onLoad", fillBio());
            break;
        case "Alex Ironside - Projects":
            document.addEventListener("onLoad", fillProjects());
            document.addEventListener("onLoad", changeSlide());
            break;
        case "Alex Ironside - Contact":
            var button = getID("sendButton");
            button.addEventListener("click", function(event) {
                event.preventDefault();
            });
            break;
    }

    // calling the clock
    document.addEventListener("onLoad", clock());

    // Shorter getElementById
    function getID(x) {
        return document.getElementById(x);
    }

    // Hide for slider
    function hide() {
        $("#slider").fadeOut(500); //One of the two jquery functions i know. Fades the image out
    }

    // A clock
    function clock() {
        var today = new Date();
        var day = today.getDate();
        if (day < 10) day = "0" + day; //makes sure there is noghting like 12/3/12
        var month = today.getMonth() + 1;
        if (month < 10) month = "0" + month; //makes sure there is noghting like 12/3/12
        var year = today.getFullYear();
        var hours = today.getHours();
        if (hours < 10) hours = "0" + hours; //makes sure there is noghting like 12:3:12
        var minutes = today.getMinutes();
        if (minutes < 10) minutes = "0" + minutes; //makes sure there is noghting like 12/3/12
        var seconds = today.getSeconds();
        if (seconds < 10) seconds = "0" + seconds; //makes sure there is noghting like 12/3/12

        var test = getID("date1").textContent = day + "/" + month + "/" + year + " | " + hours + ":" + minutes + ":" + seconds; //setting the time
        setTimeout("clock()", 1000); //refreshing the clock
    }

    // The slider
    function changeSlide() {
        number++;
        if (number > 3)
            number = 1;
        var file = "<img src=\"./Assets/pic" + number + ".png\" class=\"img-rounded\" alt=\"My projects\" id=\"picture\">" //Changing pictures
        getID("slider").innerHTML = file; //Setting the file path
        $("#slider").fadeIn(500); //One of the two jquery functions I know. Fades the image in
        setTimeout("changeSlide()", 5000); //Sets the time to the next call of changeSlide function
        setTimeout("hide()", 4500); //Calls the hide function, which triggers the fadeout. Half a second is needed to 
    }

    // Filling bio with content
    function fillBio() {
        var bioContent = getID("bioContent");
        let message = "<h1>Hi! My name is Alex</h1><p>I'm a website designer, and a web developer</p><p>My goal is to make your website as good, as fast, and as light as possible</p>";
        bioContent.innerHTML = message;
    }

    // Filling the projects with text
    function fillProjects() {
        var sliderText = getID("sliderText");
        let message = "These are some projects I've had the pleasure of working on";
        sliderText.textContent = message;
    }
})();

HTML ze sliderem

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Alex Ironside - Projects</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="./content/bootstrap/dist/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="./content/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="./scripts/lib/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="./Content/app.css">
</head>

<body id="portfolioWebsite">
    <!--Navigation part-->
    <nav class="navbar navbar-inverse">
        <div class="container">
            <div class="navbar-header"><a href="" class="navbar-brand">Iron websites</a></div>
            <ul class="nav navbar-nav">
                <li>
                    <a href="./index.html">Home</a>
                </li>
                <li class="active">
                    <a href="./projects.html">Projects</a>
                </li>
                <li>
                    <a href="./contact.html">Contact us</a>
                </li>
            </ul>
            <div class="navbar navbar-nav navbar-right" id="clock">
                <div id="date1"></div>
                <div id="date2"></div>
            </div>
        </div>
    </nav>
    <!--END of navigation-->
    <!--Header with logo and slider-->
    <header class="header">
        <div class="container">
            <div class="col-sm-3">
                <img src="./Assets/logo.svg" id="logo" alt="Logo">
            </div>
            <div class="col-sm-9">
                <img id="myPicture" src="./Assets/me.png" alt="My picture">
            </div>
        </div>
    </header>
    <!--END of logo and slider-->
    <!--Container filled with JS-->
    <div>
        <h2 id="sliderText"></h2>
    </div>
    <div class="container" id="projectsContent">
        <div id="slider">
        </div>
    </div>
    <!--END of container-->
    <!--Footer-->
    <div class="navbar-default navbar-fixed-bottom" id="footer">
        <div class="container" id="social-media">
            <a href="https://www.facebook.com/"><i class="fa fa-facebook-official fa-2x" aria-hidden="true"></i></a>
            <a href="https://www.linkedin.com/"><i class="fa fa-linkedin-square fa-2x" aria-hidden="true"></i></a>
            <a href="https://github.com/"><i class="fa fa-github-square fa-2x" aria-hidden="true"></i></a>
        </div>
        <div class="container">&copy; Alexander Ironside</div>
    </div>
    <!--END of footer-->
</body>
<script src="./scripts/lib/jquery/dist/jquery.min.js"></script>
<script src="./content/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="./scripts/app.js"></script>

</html>

HTML z formularzem
 

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Alex Ironside - Contact me</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="./content/bootstrap/dist/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="./content/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="./scripts/lib/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="./Content/app.css">
</head>

<body>
    <!--Navigation part-->
    <nav class="navbar navbar-inverse">
        <div class="container">
            <div class="navbar-header"><a href="" class="navbar-brand">Iron websites</a></div>
            <ul class="nav navbar-nav">
                <li>
                    <a href="./index.html">Home</a>
                </li>
                <li>
                    <a href="./projects.html">Projects</a>
                </li>
                <li class="active">
                    <a href="./contact.html">Contact us</a>
                </li>
            </ul>
            <div class="navbar navbar-nav navbar-right" id="clock">
                <div id="date1"></div>
                <div id="date2"></div>
            </div>
        </div>
    </nav>
    <!--END of navigation-->
    <!--Header with logo and slider-->
    <header class="header">
        <div class="container">
            <div class="col-sm-3">
                <img src="./Assets/logo.svg" id="logo" alt="Logo">
            </div>
            <div class="col-sm-9">
                <img id="myPicture" src="./Assets/me.png" alt="My picture">
            </div>
        </div>
    </header>
    <!--END of logo and slider-->
    <!--Container-->
    <div class="container" id="contactContent">
        <form>
            <div class="form-group">
                <label for="email">Email:</label>
                <input type="email" class="form-control" id="email">
            </div>
            <div class="form-group">
                <label for="name">Name:</label>
                <input type="text" class="form-control" id="name">
            </div>
            <div class="form-group">
                <label for="phone">Phone number:</label>
                <input type="text" class="form-control" id="phone">
            </div>
            <div class="form-group">
                <label for="message">Message:</label>
                <textarea name="message" class="form-control" id="message" rows="3"></textarea>
            </div>
            <button type="submit" id="sendButton" class="btn btn-default">Submit</button>
            <button type="reset" class="btn btn-warning">Reset</button>
        </form>
    </div>
    <!--END of container-->
    <!--Footer-->
    <div class="navbar-default navbar-fixed-bottom" id="footer">
        <div class="container" id="social-media">
            <a href="https://www.facebook.com/"><i class="fa fa-facebook-official fa-2x" aria-hidden="true"></i></a>
            <a href="https://www.linkedin.com/"><i class="fa fa-linkedin-square fa-2x" aria-hidden="true"></i></a>
            <a href="https://github.com/"><i class="fa fa-github-square fa-2x" aria-hidden="true"></i></a>
        </div>
        <div class="container">&copy; Alexander Ironside</div>
    </div>
    <!--END of footer-->
</body>
<script src="./scripts/lib/jquery/dist/jquery.min.js"></script>
<script src="./content/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="./scripts/app.js"></script>

</html>

 

komentarz zamknięcia: Wystarczyło wywolac funkcje w ten sposób: setTimeout(clock,1000) zamiast "clock()"

2 odpowiedzi

+1 głos
odpowiedź 2 lutego 2017 przez xmentor Nałogowiec (49,520 p.)
edycja 2 lutego 2017 przez xmentor
addEventListener("onLoad"

load powinno być

Problem polega na tym ze kazda z funkcji takich jak clock() i changeSlide() dzialaja bez problemu poza iife, lecz juz zakmniete w tymze iife wywala blad. Jak to rozwiazac?

Jeżeli są one zamknięte w IIFE to są dostępne jedynie lokalnie. Nie możesz wywołać ich poza tą funkcją natychmiastową (są sposóby by wyciągnać to co jest w IIFE do globalnego scope).

komentarz 3 lutego 2017 przez Alex.Ironside Stary wyjadacz (14,900 p.)
No wlasnie wydaje mi sie ze wywoluje. Ale konsola krzyczy ze zle wiec nie wiem co zrobilem zle.
Konsola:

VM2642:1 Uncaught TypeError: clock is not a function(anonymous function)

VM2643:1 Uncaught ReferenceError: hide is not defined(anonymous function)

VM2644:1 Uncaught ReferenceError: changeSlide is not defined
komentarz 3 lutego 2017 przez xmentor Nałogowiec (49,520 p.)
document.addEventListener(event, changeSlide());

powinno być :

element.addEventListener(event, funkcja); 
//lub 
element.addEventListener(event, function() { funkcja(); });

popraw wszystkie listenery

komentarz 3 lutego 2017 przez Alex.Ironside Stary wyjadacz (14,900 p.)
Naprawde nie chce byc chujem i sie czepiac ale nie mam pojecia czym to sie rozni od tego co mam w kodzie. Mam po prostu wywolac funkcje clock() changeSlide() i hide() poza iife?
komentarz 3 lutego 2017 przez xmentor Nałogowiec (49,520 p.)

A no różni się:

http://jsbin.com/valaniyohi/edit?js,output

Zobacz, event click a wywołuje funkcje od razu bez klikania ;)

Jeżeli chcesz, żeby funkcja wywołana została po załadowaniu DOM-u to powinno wyglądać tak:

document.addEventListener('DOMContentLoaded', mojaFunkcja);

Aczkolwiek taki zabieg jest nie potrzebny, wystarczy, że skrypt jest umieszczony na koncu ciała dokumentu.Wtedy po prostu wywołaj funkcje.

(function() {
  function saySomething(something) {
    alert(something);
  }
  saySomething('Something');
}())

Myślę, że nie trudno to zrozumieć.

komentarz 3 lutego 2017 przez Alex.Ironside Stary wyjadacz (14,900 p.)
I setTimeout tez w iife?
+1 głos
odpowiedź 2 lutego 2017 przez Kornelia Kobiela Nałogowiec (33,340 p.)

Jeżeli chcesz cokolwiek wyciągnąć z IIFE na zewnątrz to robisz tak:

const a = (function{
  return{ 
    b:function(){
    }
  }
})();

const b = a.b();

Inaczej to nie będzie działać.

komentarz 3 lutego 2017 przez Alex.Ironside Stary wyjadacz (14,900 p.)
Czyli to tak jakbym ta funkcje wywolal spoza iife?

Podobne pytania

0 głosów
2 odpowiedzi 164 wizyt
pytanie zadane 14 marca 2016 w JavaScript przez artimal Gaduła (4,800 p.)
0 głosów
2 odpowiedzi 218 wizyt
pytanie zadane 1 czerwca 2017 w JavaScript przez crova Użytkownik (940 p.)
0 głosów
1 odpowiedź 168 wizyt

92,632 zapytań

141,502 odpowiedzi

319,882 komentarzy

62,015 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!

...