0

How do I invoke a private method from a public one and vice versa if I follow the plugin authoring guide?

I usually declare the private methods within the init method like:

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.

It might be the incorrect thing to do?

jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • Why is it any different with the plugin guide? This might help http://stackoverflow.com/questions/6420825/call-private-method-from-public-method – elclanrs Feb 21 '12 at 07:34
  • I see...I'm finding out things as I go. These might help, [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 Feb 21 '12 at 08:07

1 Answers1

1

If by 'this context correct' you mean that you want call some public method with this set to value which this has inside trimSpaceInSelection then you can do it like this:

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

And if you want set this inside public method to current jQuery collection then:

....
this.trimSpaceInSelection = function () {
    methods.somePublicMethod.apply($this, arguments); // this will pass all arguments passed to trimSpaceInSelection to somePublicMethod
}
....
Mateusz W
  • 1,981
  • 1
  • 14
  • 16
  • Works like a charm. thanks. I do this to create the args array: `var args = [];args[0] = actionName;` are there a nicer way to do it? – jgauffin Feb 21 '12 at 11:16
  • I just declare that before calling `methods.somePublicMethod.apply($this, arguments);` in your example. – jgauffin Feb 21 '12 at 12:02
  • you can do in two ways: `methods.somePublicMethod.call($this, firstArg, secondArg, thirdArg);`, or `methods.somePublicMethod.apply($this, [firstArg, secondArg, thirdArg]);` This can help: http://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply – Mateusz W Feb 21 '12 at 12:03