EMiller
EMiller

Reputation: 1148

jQuery plugin scope of settings passed in

I feel like this must have been asked, but I'm unable to find it through my searches.

Here's a complete example of the issue that's confusing me:

<html><head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
(function($){
    $.fn.testPlugin = function(options){
    settings = $.extend({val : "default"}, options);
    return this.each(function(){
        $(this).click(function(e){ 
        e.preventDefault();
        console.log(settings.val);
        });
    });
    }
 })(jQuery);

$(document).ready(function(){
    $('a#a1').testPlugin();
    $('a#a2').testPlugin({val : 'new val'});

});
</script>
</head><body>
<a href="#" id="a1">A1</a>
<a href="#" id="a2">A2</a>
</body>
</html>

Clicking on either link will log "new val" to your firebug console. You can probably imagine that I want the first link to keep the default settings, and the second to have my overwritten settings. There must be a standard pattern for achieving this for a plugin?

Upvotes: 1

Views: 1012

Answers (1)

meder omuraliev
meder omuraliev

Reputation: 186562

I think you need to use var to keep the settings variable in scope. Try:

 $.fn.testPlugin = function(options){
        var settings = $.extend({val : "default"}, options);
        return this.each(function(){
            $(this).click(function(e){ 
                e.preventDefault();
                console.log(settings.val);
            });
        });
    }

Upvotes: 5

Related Questions