开发者

jquery plugin call public function inside other public function

开发者 https://www.devze.com 2023-02-25 14:04 出处:网络
I defined my plugin base on http://docs.jquery.com/Plugins/Authoring (function( $ ){ var methods = { init : function( options ) {},

I defined my plugin base on 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 );

How to call the show method inside the update method?

EDIT:

The show method references this. Using methods.show(options) or methods['show'](Array.prototype.slice.call( arguments, 1 )); works to call the show method but then the reference to this seems to be wrong because I got a this.find(...) is not a function error.

The show method:

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


var methods = {
  init : function( options ) {  },
  show : function( options ) {  },
  hide : function( ) {  },
  update : function( options ) { 

    methods.show.call(this, options);

  }
};


Your use of .apply is what's throwing everything off here. You're deliberately changing what this means, which is what makes this.show() not work. If you want this to continue to be methods (which makes sense), you can do simply:

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

精彩评论

暂无评论...
验证码 换一张
取 消