KodeFor.Me
KodeFor.Me

Reputation: 13511

How to run a statement only once for any instance of the plugin?

I am writting a plugin for jQuery, and I am wondering if there is way to call a method that affect any instance of the plugin only once.

More specific, I have code that look like the following:

var body = $('body');

body.on(
    'click',
    'selector',
    function(e)
    {
        console.log("Do some stuff with my plugin");
    }
);

In the above code, the "console.log("Do some stuff with my plugin");" is running for the same ammount of plugin instances.

In example, if I have the following code:

<body>
    <a href="#" class="selector_1">Click me</a>
    <a href="#" class="selector_2">Click me</a>
    <a href="#" class="selector_3">Click me</a>
    <script type="text/javascript">
        jQuery(document).ready(
            function($)
            {
                $('.selector_1').myPlugin();
                $('.selector_2').myPlugin();
                $('.selector_3').myPlugin();
            }
        );
    </script>
</body>

Now if I click any of the links in my document, I will get three times the message "Do some stuff with my plugin" in my console, because this event is three times registered.

So, is there a way to run some code only once for any amount of plugin instances ?

Note : To build my jQuery plugin I have use this skeleton

Upvotes: 0

Views: 81

Answers (1)

Richard Dalton
Richard Dalton

Reputation: 35793

Easiest way would be to add a flag to the body element to state that the plugin has already been initialised and check this before binding the event again:

var body = $('body');
// If plugin has not already bound event
if (!body.data('myplugin-init')) {
    body.on(
        'click',
        'selector',
        function(e)
        {
            console.log("Do some stuff with my plugin");
        }
    );
    // Flag that event has been bound
    body.data('myplugin-init', true);
}

Upvotes: 1

Related Questions