我的第一个jQuery插件,函数和全局变量在哪里?

时间:2011-04-13 23:25:14

标签: jquery jquery-plugins

我正在编写我的第一个jQuery插件,并且我有一些关于我应该放置东西的问题。我试着四处寻找,但似乎有不同的方法来构建插件,所以我迷路了。我通过关注jQuerys网站上的Authoring Plugins文档得到了这一点,但不知道下一步该去哪里。

  1. 我在哪里放置一个常用功能?以hello()为例。假设我打算在整个插件中使用该功能,它应该在哪里生活?现在我把它放在顶部,这似乎有用,但我不确定这是正确的做法。

  2. 我在哪里放置一个全局变量?以我的变量“imgs”数组为例。我应该在现在或在我的init方法或其他地方声明这个吗?

    (function($){
    
    function hello(){
        alert("hello world");
    }
    var imgs = new Array(); 
    
    var methods = {
        init: function(options){
            if(options){
                $.extend({
                    width: 200,
                    height: 200,                        
                    selectedColor: '#123456'
                }, options);    
    
                // for every image do something
                this.find('img').each(function(){   
                    var $this = $(this);
    
                    var width = $this.width();
                    var height = $this.height();
    
                    console.log("width: " + width + " height: " + height);
    
                    selection = function() {
                        console.log($this.attr('src'));                         
                        hello();                
                    };
    
                    $this.bind('click', selection);                     
                });                 
            }               
            return this;        
        },
        test : function( string ) {
            console.log("Test: " + string);                 
            //return "here";
        }
    };
    
    
    $.fn.Thumbnails = function(method) {      
        // Method calling logic
        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 on jQuery.Thumbnails' );
        }             
    
    };
    
    })(jQuery);
    
    $thumbnails = $('#imagescontainer').Thumbnails({
            height: 150,
    });
    
  3. 感谢您的帮助!

1 个答案:

答案 0 :(得分:8)

  1. 将它们放在jQuery函数之外,但在自执行函数中。这将确保它们仅存在于您的jQuery函数中。例如,您可以看到实用程序函数findText()在我的插件bumpyText中的jQuery函数之外。

  2. 这取决于其所需的生命周期。如果您在每次调用函数时都需要它,请将其放在函数中。如果它应该保持每个插件调用的状态(不太可能),将它放在jQuery函数之外。