ZhouMengkang
ZhouMengkang

Reputation: 193

what's wrong with this function (the testFunction)

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
        <title>test</title>
        <style type="text/css">
        .button_test{
            border-radius: 4px;
            padding: 4px;
            cursor: pointer;
            background-color:#999; 
        }
        </style>
    </head>
    <body>
        <span class="button_test">debug</span>
        <script type="text/javascript">
        var testFunction = function(_callback){
            $(".button_test").click(function(){
                if ("function"==typeof(_callback)) {
                    _callback();
                };
            })
        }
        testFunction(function(){
            console.log(111);
        });
        </script>
    </body>
</html>

The function testFunction has been used only once, so I think when I clcik $(".button_test") at the first time, the console will output 111. Then no matter how many times I click $(".button_test") ,the console would output nothing.
However, in fact, everytime $(".button_test") being clicked, the console would output 111.

Upvotes: 0

Views: 74

Answers (3)

Vince
Vince

Reputation: 4222

It's not testfunction that's attached to .button_test as the click handler, but that anonymous function that executes console.log(111).

Nothing changes the click handler on .button_test after that one time you run testfunction, so the button continues to execute console.log(111) every time.

Upvotes: 0

epascarello
epascarello

Reputation: 207501

Click does not run an event once, it runs every single time the event occurs. Only way to stop it would be to unbind the event or add a flag inside to say not run. BUT there is a better way because jQuery has a method in to run an event once, that would be one()

one()

.one( events [, data ], handler(eventObject) ) Returns: jQuery

Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

And your code can use it like this

    var testFunction = function(_callback){
        $(".button_test").one("click", function(){
            if ("function"==typeof(_callback)) {
                _callback();
            };
        })
    }
    testFunction(function(){
        console.log(111);
    });

Upvotes: 2

Johnny5
Johnny5

Reputation: 6862

You are registering a click event handler on .button_test. Unless you unbind the event, it will be launched each time you clic on the element.

The behavior you describe is the expected behavior.

See the doc for click and/or bind.

Upvotes: 1

Related Questions