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
jgauffin
101k45 gold badges245 silver badges378 bronze badges
-
Why is it any different with the plugin guide? This might help stackoverflow.com/questions/6420825/…elclanrs– elclanrs2012年02月21日 07:34:46 +00:00Commented Feb 21, 2012 at 7:34
-
I see...I'm finding out things as I go. These might help, 1, 2, 3elclanrs– elclanrs2012年02月21日 08:07:23 +00:00Commented Feb 21, 2012 at 8:07
1 Answer 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
Mateusz W
2,0311 gold badge15 silver badges16 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
jgauffin
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
I just declare that before calling
methods.somePublicMethod.apply($this, arguments); in your example.Mateusz W
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/… lang-js