jQuery插件创作和命名空间 [英] jQuery Plugin Authoring and Namespacing

查看:89
本文介绍了jQuery插件创作和命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于这样编写插件:

;(function($){jQuery.fn.myPlugin=function(options){
    var defaults={
        'property':value
    },
    o=$.extend({},defaults,options||{});

   // INSERT AND CACHE ELEMENTS
   var $Element=$('<div></div>');
   $Element.appendTo($('body'));

function funFunction(){
  // I have access to $Element!
 $Element.hide(500);
};

this.each(function(i){
     var $this=$(this);
});
return this;
});};})(jQuery);

我知道它并不完美,这就是为什么我现在试图正确学习命名空间,更好的插件结构/样式的原因.不幸的是,我读过的前几本书参考了jQuery插件编写教程的逐字逐句,因此并没有太大帮助.该教程似乎将所有内容拆分开来,并且没有显示一个很好的组合示例,这就是为什么我很困惑.在本教程中,它显示了命名空间示例.

I know it's not perfect, which is why I'm now trying to properly learn namespacing, better plugin structure/patterns. The past couple of books I've read unfortunately reference the jQuery plugin authoring tutorial word for word, so haven't been much help. The tutorial seems to split everything up and doesn't show a good example of a combination, which is why I'm confused. In the tutorial, it shows the namespacing example.

jQuery插件命名空间教程

(function( $ ){
  var methods = {
    init : function( options ) { 
    },
    show : function( ) {
    },
    hide : function( ) { 
    },
    update : function( content ) { 
    }
  };

  $.fn.tooltip = 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.tooltip' );
    }    
  };
})( jQuery );
// calls the init method
$('div').tooltip(); 

我了解结构以及如何访问命名空间对象,但是它显示了默认/选项的另一个示例,不包括任何命名空间...因此,为了编写一个正确命名空间的插件的开头,请使用默认/选项并缓存要插入的HTML元素以供整个插件使用,我提出了以下建议.

I understand the structure and how to access namespaced objects, however it shows the other example for defaults/options excluding any namespacing... So in an effort to write the beginning of a plugin that is properly namespaced, has defaults/options and caches the HTML elements I'm inserting for use throughout the entire plugin, I've come up with the following.

正确的组合吗?

;(function($,window,document,undefined){
var myPlugin={
    // METHODS
    init:function(options){

    },
    buildElements:function(){ 
        var $Elements=$('<div id="myElem"></div>')
                    .appendTo($('body'));
       }
};

$.fn.myPlugin=function(method,options){
    var defaults={

    },
    options=$.extend({},defaults,options||{});

    myPlugin.buildElements();

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

  1. 很明显,当我构建/插入myElem时,它将仅在该方法内部可用,而在其他任何方法内部均不可用....我在错误的位置构建它吗?

  1. Obviously, when I build/insert myElem it will only be available inside that method and not inside any others.... am I building it in the wrong place?

默认值/扩展名是否在正确的位置?

Is the defaults/extend in the correct place?

如果我不想从插件外部访问方法,是否需要方法逻辑部分?

If I'm not wanting to access methods from outside of the plugin do I need the method logic section?

使用.prototype与.fn有什么好处吗?

Are there any benefits to using .prototype vs .fn?

非常感谢任何人和所有人! :)

Thanks so much to anyone and everyone! :)

推荐答案

更仔细地查看工具提示"示例插件.这是一个真正的伟大模式.

Look at the "tooltip" example plugin more carefully. It's a truly GREAT pattern.

它完成了您需要的所有命名空间,并且已经是您惯用的类型,至少底部的通用"supervisor"块是-即此部分:

It does all the namespacing you'll ever need and is already of the type you're used to, at least the generalised "supervisor" block at the bottom is - ie this part :

$.fn.tooltip = 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.tooltip' );
    }    
};

methods是用strightforward javascript术语表示的私有变量,但是它的属性由主管以非常巧妙,非常规的方式作为插件的方法公开.

methods is a private variable in strightforward javascript terms but its properties are exposed as methods of the plugin in a very clever, unconventional way by the supervisor.

Pleeeease不要尝试将默认值/选项代码移出init方法.这将把所有东西都弄错了!遵循尝试和信任的模式,一切都会好的.

Pleeeease don't try to move the defaults/options code out of the init method. This will screw everything sideways! Follow the tried and trusted pattern and all will be fine.

请务必遵循模式的其他方面:

Be sure to adhere to other aspects of the pattern :

  • 要保持jQuery对象的可链接性,请在每个不返回特定结果的方法中使用return this.each(function(){...})结构.
  • (通常)在初始化时建立一个.data('pluninName', {...})对象,以容纳初始化时建立的所有数据,以后需要其他插件方法对其进行访问/修改/增强.
  • To maintain jQuery object chainability, use a return this.each(function(){...}) structure in every method that doesn't return a specific result.
  • (Generally), in init, establish a .data('pluninName', {...}) object to accommodate any data that is established on initialization, and that needs to be accessed/modified/augmented later by other plugin methods.

该模式仅为插件本身提供一个封闭(包含methods对象);闭包的名称空间不能用于元素特定的数据(包括初始化选项),因此需要使用.data('pluninName', ...).

The pattern provides only a single closure for the plugin itself (containing the methods object); the closure's namespace cannot be used for element-specific data (including initialization options), hence the need to use .data('pluninName', ...).

这些不仅仅是约定-它们绝对是使模式按预期工作的关键.

These are not just conventions - they are absolutely key to making the pattern work as intended.

这篇关于jQuery插件创作和命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆