2012-04-05 10 views
0

jqueryプラグインを使用していますが、後で使用するためにプロパティを保存する際に問題が発生しています。次の例では、18, 50, 18を探しているときにコンソール出力は18, 50, 50です。私はなぜこれが起こっているのか理解していますが、複数の異なる方法で使用するためにpropertiesを保存する良い方法を理解することはできません。私は何か非常に明白なものを見逃している気がしますが、私はそれを見ていません。jQueryプラグインの保存値

<html> 
    <body> 
     <h1>Hello</h1> 
     <h2>World</h2> 

     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> 
     <script type="text/javascript"> 
      (function ($) { 
       var commonOperations, methods, properties; 

       commonOperations = function() { 
        console.log(properties.height); 
       }; 

       methods = { 
        init : function (overrides) { 
         var defaults; 
         defaults = { height: 18 }; 
         properties = $.extend(defaults, overrides); 

         commonOperations(); 
        }, 

        foo : function() { 
         commonOperations(); 
        } 
       }; 

       $.fn.myPlugin = function (method) { 
        if (methods[method]) { 
         return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
        } else if (typeof method === 'object' || !method) { 
         return methods.init.apply(this, arguments); 
        } else { 
         $.error('Method ' + method + ' does not exist for jQuery.myPlugin'); 
        } 
       }; 
      }(jQuery)); 

      $(document).ready(function() { 
       $("h1").myPlugin(); 
       $("h2").myPlugin({ height: 50 }); 
       $("h1").myPlugin("foo"); 
      }); 
     </script> 
    </body> 
</html> 

答えて

2

それはあなたのプラグインの性質に依存するが、それは要素ごとのベースでプロパティを格納するために.data()を使用することが理にかなっている可能性があります。

init: function(overrides) { 
    return this.each(function() { 
     var defaults = { whatever: "foo" }; 
     $(this).data('properties', $.extend(defaults, overrides)); 
    }); 
    } 

その後、他の方法は、常に要素から「プロパティ」オブジェクトを引っ張る:

foo : function() { 
     return this.each(function() { 
     commonOperations.call(this, $(this).data('properties')); 
     }); 
    } 
+1

+1を - サポート情報はここで見つけることができます:http://docs.jquery.com/Plugins/オーサリング#データ –

+0

ありがとうございます。それは完璧な意味合いがあります。 – Jason

関連する問題