【问题标题】:jquery plugin call public function inside other public functionjquery插件在其他公共函数中调用公共函数
【发布时间】:2011-04-13 20:23:50
【问题描述】:

我基于http://docs.jquery.com/Plugins/Authoring定义了我的插件

(function( $ ){

  var methods = {
    init : function( options ) {  },
    show : function( options ) {  },
    hide : function( ) {  },
    update : function( content ) { 
      // How to call the show method inside the update method
      // I tried these but it does not work
      // Error: not a function
      this.show(); 
      var arguments = { param: param };
      var method = 'show';
      // Error: options is undefined
      methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));  
    }
  };

  $.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 );

如何在update方法中调用show方法?

编辑

show 方法引用this。使用methods.show(options)methods['show'](Array.prototype.slice.call( arguments, 1 )); 可以调用show 方法,但随后对this 的引用似乎是错误的,因为我遇到了this.find(...) is not a function 错误。

show 方法:

show: function(options) {
    alert("Options: " + options);
    alert("Options Type: " + options.interactionType);
    var typeCapitalized = capitalize(options.interactionType);
    var errorList = this.find('#report' + typeCapitalized);
    errorList.html('');
},

【问题讨论】:

    标签: jquery jquery-plugins


    【解决方案1】:
    var methods = {
      init : function( options ) {  },
      show : function( options ) {  },
      hide : function( ) {  },
      update : function( options ) { 
    
        methods.show.call(this, options);
    
      }
    };
    

    【讨论】:

    • 我编辑了这个问题,因为现在我在 show 方法中遇到了问题,因为引用了 this
    • apply 的第二个参数必须是一个数组。所以我尝试了methods.show.apply(this, Array.prototype.slice.call( arguments, 1 ) );var arguments = { interactionType: 'Request' };,但现在show 方法中的options 是未定义的。
    • arguments 是一个特殊的对象,不要尝试声明自己的对象。无论如何,我再次编辑了我的问题 - 使用 Function.call 而不是 Function.apply。 (对不起,我不能先测试这些东西,如果你有一个我可以检查的 jsfiddle 会有所帮助)
    【解决方案2】:

    您对.apply 的使用使这里的一切都被抛弃了。你故意改变 this 的意思,这就是this.show() 不起作用的原因。如果您希望 this 继续成为 methods(这是有道理的),您可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多