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?

asked Feb 21, 2012 at 7:28
2
  • Why is it any different with the plugin guide? This might help stackoverflow.com/questions/6420825/… Commented Feb 21, 2012 at 7:34
  • I see...I'm finding out things as I go. These might help, 1, 2, 3 Commented Feb 21, 2012 at 8:07

1 Answer 1

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
}
....
answered Feb 21, 2012 at 8:07
Sign up to request clarification or add additional context in comments.

3 Comments

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?
I just declare that before calling methods.somePublicMethod.apply($this, arguments); in your example.
you can do in two ways: methods.somePublicMethod.call($this, firstArg, secondArg, thirdArg);, or methods.somePublicMethod.apply($this, [firstArg, secondArg, thirdArg]); This can help: stackoverflow.com/questions/1986896/…

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.