2012-04-05 27 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/編寫#數據 – 2012-04-05 21:41:28

+0

謝謝。這很有道理。 – Jason 2012-04-05 21:43:52