简体   繁体   中英

Two clicks to perform button action with requirejs?

I have this code:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="lib/require.js" data-main="app"></script>
</head>
<body>
<button id="remover">Remove</button>
</body>
</html>

app.js

require.config({
    paths: {
        'jquery': 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min',
        'mylib': 'applib/mylib'
    }
});

require(['mylib'], function(teller){
    teller.tell('Hello there');

    $(function(){
        $('#remover').on('click', function(){
            teller.remove();
        })
    })
});

mylib.js

define(['jquery'], function($){
    var tell = function(msg){
        $('body').append( $('<p>').text(msg).addClass('teller') );
    };

    var remove = function(){
        $('#remover').on('click', function(){
            $('body').find('.teller').remove();
        });
    };


    return {
        tell: tell,
        remove: remove
    }
});

I don't understand, why it takes two clicks for the button to remove the element. Could anyone explain to me?

Your remove function in mylib.js doesn't also need to listen for the click because you are already listening to the click in app.js.

You can change your remove function to:

var remove = function(){
    $('body').find('.teller').remove();
};

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