parameter is outside the plugin. You have to declare them inside
$.fn.sample so they all will have the same scope:
(function($) {
$.fn.sample = function(options) {
// local variable bound to the current instance:
var parameter = options.parameter1;
// now this method has access to the private member:
$.fn.showParameter = function() {
alert(parameter);
}
return this.each(function() {
// processing code here
});
}
})(jQuery);
A bit more on this subject:
http://groups.google.com/group/jquery-en/browse_thread/thread/9dc9be1cc298cbdd/3e7a4b00ead74dd9
On Oct 31, 1:22 pm, dns <donaldsno...@hotmail.com> wrote:
> I'm developing a plugin and I'm having some issues. I put together a
> small test plugin to demonstrate the problem I'm having.
>
> Here's the sample plugin. It simply saves a parameter passed into the
> plugin into a local variable, and displays that variable at a later
> time.
>
> (function($) {
> // local variable
> var parameter = "not set";
>
> // Prototype Methods
> $.fn.extend({
>
> sample: function(options) {
>
> parameter = options.parameter1;
>
> return this.each(function() {
> // processing code here
> });
> },
>
> showParameter: function() {
> alert(parameter);
> }
> });
>
> })(jQuery);
>
> This simple plugin works fine if I only use 1 DOM element. The
> problem occurs when I use this plugin on multiple divs. For example,
> consider this html page:
>
> <html>
> <head>
> <title></title>
> <script type="text/javascript" src="../js/jquery-1.2.6.min.js"></
> script>
> <script type="text/javascript" src="../js/jquery.sample.js"></
> script>
>
> <script type="text/javascript">
> var sample1;
> var sample2;
>
> $(function() {
> sample1 = $("#div1").sample({
> parameter1 : "This is parameter 1111111111"
> });
>
> sample2 = $("#div2").sample({
> parameter1 : "This is parameter 2222222222"
> });
>
> sample1.showParameter();
> sample2.showParameter();
> });
> </script>
>
> </head>
> <body>
> <div id="div1"></div>
> <div id="div2"></div>
> </body>
> </html>
>
> The problem I am having is that both variables (sample1 and sample2)
> in the html page display the alert "This is parameter 2222222222". I
> was expecting the variable sample1 to display "This is parameter
> 1111111111" and variable sample2 to display "This is parameter
> 2222222222".
>
> I've tried many different plugin patterns (for examplehttp://www.learningjquery.com/2007/10/a-plugin-development-pattern)
> but no luck. It's almost like my parameter in the plugin has global
> scope (maybe it does and it's just my lack of javascript knowledge).
>
> Any thoughts, feedback, or suggestions would be appreciated.
>
> Thanks.
No comments:
Post a Comment