Плагин jquery вызывает открытую функцию внутри другой открытой функции - PullRequest
5 голосов
/ 14 апреля 2011

Я определил базу своего плагина на 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 );

Как вызвать метод show внутри метода обновления?

EDIT :

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('');
},

Ответы [ 2 ]

14 голосов
/ 14 апреля 2011
var methods = {
  init : function( options ) {  },
  show : function( options ) {  },
  hide : function( ) {  },
  update : function( options ) { 

    methods.show.call(this, options);

  }
};
1 голос
/ 14 апреля 2011

Ваше использование .apply - вот что отбрасывает все здесь. Вы сознательно меняете , что означает this, и именно поэтому this.show() не работает. Если вы хотите, чтобы this продолжал быть methods (что имеет смысл), вы можете просто сделать:

  return methods[ method ](Array.prototype.slice.call( arguments, 1 ));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...