views:

228

answers:

1

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"&gt;&lt;/script&gt;
<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?

+4  A: 

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);
            });
        });
    }
meder
updated - i think i confused myself with the $.extend argument order.
meder
ugh, of course ... var. Thanks
EMiller