简体   繁体   中英

Event Listener Best Practices for web app

I'm making a web app, and my javascript is collecting quite a few $(document).on event listeners. It is working well enough for me, but it feels like there is must be a better way to organize it. Here's a sample:

    // send quiz info via Ajax, then load form for the first question.
    $(document).on('click', '#create-new-quiz', function(){
        createNewQuiz();
        $('#forms').load("dash/workspace.php", {
            action : 'get-new-question'
        });
    }); 

    // load the form to create the first question
    $(document).on('click', '#finish-quiz', function(){
        addQuestion();
        $('#forms').load("dash/workspace.php",{
            action : 'finish-quiz'
        });
    }); 

    //call function to add a new question via ajax when the button is clicked. 
    $(document).on('click', '#add-question', function(){
        nextAction = "add-question";
        addQuestion();
    });

That shows that I have a variety of buttons that are dynamically added and removed form the DOM. When they are clicked, a function is called.

Any suggestions? Am I already on the right path, or is there a better way to organize this?

I find the $('#button').click(function(){}) shortcut to be tidier.

Also, your first two event handlers are fairly similar and could be made a bit more generic ie passed an action as a variable:

$('.quizButton').click(function(e){
    createNewQuiz();
    $('#forms').load("dash/workspace.php", {
        action : $('this').data('action');
    });
}); 

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