2012-02-21 1 views
0

Comment invoquer une méthode privée à partir d'une méthode publique et vice versa si je suis le plugin authoring guide?Appel de méthodes de plugin

Je déclare généralement les méthodes privées dans la méthode init comme:

var methods = { 
    init: function(options) { 
     var settings = $.extend({ 
     }, options); 

     return this.each(function() { 
      var $this = $(this); 
      var data = $this.data('griffin-editor'); 


      this.trimSpaceInSelection = function() { 
       //how do I call a public method here? 
       //to get the this context correct. 
      } 

      if (typeof data !== 'undefined') { 
       return this; 
      } 

      //the rest of the code. 

Il pourrait être la chose à faire incorrecte?

+0

Pourquoi est-il différent avec le guide plugin? Cela pourrait aider http://stackoverflow.com/questions/6420825/call-private-method-from-public-method – elclanrs

+0

@elclanrs: Voir ma mise à jour. – jgauffin

+0

Je vois ... Je découvre des choses comme je vais. Ceux-ci pourraient aider, [1] (http://stefangabos.ro/jquery/jquery-plugin-boilerplate-revisited/), [2] (http://stackoverflow.com/questions/2061501/jquery-plugin-design- pattern-common-practice-for-dealing-with-private-functio), [3] (http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html) – elclanrs

Répondre

1

Si par « ce contexte correct » vous voulez dire que vous voulez appeler une méthode publique avec cet ensemble à la valeur que cela a l'intérieur trimSpaceInSelection alors vous pouvez le faire comme ceci:

.... 
this.trimSpaceInSelection = function() { 
    methods.somePublicMethod.apply(this, arguments); // this will pass all arguments passed to trimSpaceInSelection to somePublicMethod 
} 
.... 

Et si vous voulez définir cette méthode public à l'intérieur de la collection actuelle jQuery alors:

.... 
this.trimSpaceInSelection = function() { 
    methods.somePublicMethod.apply($this, arguments); // this will pass all arguments passed to trimSpaceInSelection to somePublicMethod 
} 
.... 
+0

Fonctionne comme un charme. Merci. Je fais cela pour créer le tableau args: 'var args = []; args [0] = nom_action;' y at-il une meilleure façon de le faire? – jgauffin

+0

Pouvez-vous afficher le code complet, par ex. le mettre sur jsfiddle.net? –

+0

Je viens de déclarer cela avant d'appeler 'methods.somePublicMethod.apply ($ this, arguments);' dans votre exemple. – jgauffin