试图学习jQuery插件开发

时间:2011-02-04 16:57:00

标签: javascript jquery plugins

所以我正在尝试学习如何基于此示例实现插件的方法集合:http://docs.jquery.com/Plugins/Authoring

我无法理解的是,如何将插件默认扩展的选项发送到各个方法。

我很确定任何原始选项都会发送到此方法:

return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));

那么如何使用默认值扩展这些参数?该示例并未真正定义如何执行此操作...

var methods = {
      init : function( options ) {

           return this.each(function(){
               $(window).bind('resize.tooltip', methods.reposition);
           });

       }
}

此外,以下是示例插件创作页面中的代码:

    (function( $ ){

  var methods = {
     init : function( options ) {

       return this.each(function(){
         $(window).bind('resize.tooltip', methods.reposition);
       });

     },
     destroy : function( ) {

       return this.each(function(){
         $(window).unbind('.tooltip');
       })

     },
     reposition : function( ) { // ... },
     show : function( ) { // ... },
     hide : function( ) { // ... },
     update : function( content ) { // ...}
  };

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

  };

})( jQuery );

2 个答案:

答案 0 :(得分:3)

看起来我之前的回答比我之前的想法更接近标记。

是的,这一行传递了参数:

return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));

使用.apply(),您可以调用方法,更改其上下文(this值),并为其提供一组参数而不是单个参数。如果您不知道如何传递参数,那就很方便了。

所以你可以像这样打破上面一行:

  // reference the arguments passed to the plugin
var args = arguments;

  // eliminate the first one, since we know that's just the name of the method
args = Array.prototype.slice.call( arguments, 1 )

  // call the method that was passed, 
  //    passing along the Array of the arguments (minus the first one),
return methods[method].apply( this, args);

// Note that it is being called from the context of "this" which is the jQuery object

因此,如果插件被调用如下:

$('.someElem').tooltip('destroy', 'someArg', 'anotherArg' );

代码将找到"destroy"方法,将"destroy"切片离开Arguments对象,然后调用"destroy"传递剩余参数数组。

答案 1 :(得分:1)

您使用$.extend(existingObject || {} (new object), oneObject, secondObject, nthObject)

var mydefaults = { myDefaultArg : "foo" }
var inputOptions = { myDefaultArg : "Somethin else" }

var options = $.extend({}, mydefaults, inputOptions);

options.myDefaultArg == "Somethin else";

要访问数据或保存数据,您可以使用数据方法

所以,如果您在插件中,“this”是jquery元素元素,您现在可以将数据保存到其中。

$(this).data("pluginname.somedataname", data);

并检索

var data = $(this).data("pluginname.somedataname");