簡體   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