繁体   English   中英

具有方法和回调的jQuery插件

[英]jQuery plugin with methods and callback

我正在为jQuery插件开发一种“一劳永逸”的基本框架。 我基于此处找到的jQuery Plugins / Authoring示例的结构。

这是我正在构建的结构的进一步简化版本:

(function( $ ){
  var methods = {
     init : function( options ) { 
        var defaults = {
            // place default settings for plugin here
        }

        var options = $.extend(defaults, options);

        return this.each(function(){
            var $this = $(this),
                data = $this.data('PLUGINNAME'); 

            if ( ! data ) { 
             // do more setup stuff here
            }
        });
     },

     destroy : function( ) { 
       return this.each(function(){ 
        // do stuff to destroy any function binding
       })
     },

     update : function( content ) { 
        return this.each(function() { 
            //do your update stuff here
        })
     }
  };

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

我现在想弄清楚的部分是如何向插件调用添加回调函数。 我知道我需要另一个这样的参数:

  $.fn.PLUGINNAME = function( method, callback ) {

但我不确定如何根据目前的情况执行该操作。

要调用回调函数,可以使用.call方法。

init : function( options, callback ) { 
    callback.call(this, options);

在示例中,我传入了选项,但是您可以传入任何所需的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM