【问题标题】:jQuery plugin with methods and callback带有方法和回调的 jQuery 插件
【发布时间】:2012-01-07 17:00:09
【问题描述】:

我正在为 jQuery 插件开发一种全能的基本框架。我的结构基于找到 here 的 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 ) {

但我不确定如何根据我目前拥有的内容来实现它。

【问题讨论】:

  • 这个回调应该做什么以及它的签名是什么?
  • 回调应该做什么并不重要。也许它只是一个函数,需要等到插件运行一些脚本(如 getJSON 调用)才能处理页面上的某些元素。

标签: javascript jquery plugins jquery-plugins methods


【解决方案1】:

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

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

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

【讨论】:

  • 但是,使用return this.each(function(){ return 允许的插件的可链接性想法如何工作?
  • 回调不会影响“this”,因此只要您返回“this”,它将保持可链接。您可以查看一些允许回调的 jQuery 默认函数,以查看它们传入的参数。
  • 那么我的更新方法会是这样吗? update : function( options, callback ) { return this.each(function() { callback.call(this, options); }) }插件本身有什么变化吗?
  • 不幸的是,这似乎不适用于我目前的结构。稍后我将不得不重新访问。
猜你喜欢
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-08
  • 2011-05-16
  • 1970-01-01
  • 2011-06-17
相关资源
最近更新 更多