简体   繁体   中英

How to make function execute only once in JS / JQuery

i have a structure like this :

// App.js
var APP = {
    viewIndex: function(){
        EVT.doSomething();
    },

    // Another function below
}

// Event.js

var EVT = {
    doSomething: function(){
        deleteField();

        function deleteField(){
            $("body").on("click", "#btn", function(){
                console.log("Clicked");
            })
        }
    }
}

my project is SPA wannabe, so when i want to change the page, it must execute some function inside App.js , but my problem is, when i call APP.viewIndex() (when i go to Index, go back, and go to index again(without refreshing page) ) , the function inside EVT -> doSomething() is execute twice, so i have no idea how to prevent it,

in my console i got this :

Clicked

Clicked

*sorry if my explanation is a bit complicated

hope you guys can help me out of this problem :D

thanks

Use a property to remember if you already called deleteField() .

var EVT = {
    didSomething: false,
    doSomething: function(){
        if (!this.didSomething) {
            deleteField();
            this.didSomething = true;
        }
        function deleteField(){
            $("body").on("click", "#btn", function(){
                console.log("Clicked");
            })
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM