views:

60

answers:

1
(function($) {

$.fn.myFoo= function (o){
    this.element = $(this)

    options = jQuery.extend({
         name: "defaultName",
         size: 5,
         global: true
      }, o);

    _min = function (){ //am i private method?
        alert('dud');
    }
    max = function (){ //am i public method?
        alert('max');
    }
    return this.o(); //o= 'max'
}
})(jQuery);

Question 1 = is there a way to call the max method/function above if i was to use this line $('#id').myFoo('max'); Question 2 = i know that on jquery widgets an underscore "_" would mark the method as private. is this the same case on the $.fn ?

note that the line return this.o(); it is wrong its just there to demonstrate what i would like to accomplish

+2  A: 

Your code has some issues:

First, when you run it, you will end up with three global variables, max, _min and options.

JavaScript is function-scoped, but you should use the var statement to declare variables, if you don't use it, and the identifier you make the assignment is not found in the scope-chain, they will become properties of the Globlal object (window).

Second, I think you want to invoke a function passed as a String argument, if is that, you I would recommend you to use an object to group your functions, and be able to get them, if you just define your functions as variables, they are not bound to an accessible object (technically variables, arguments and function declaration identifiers are bound to the non accessible Variable Object), e.g.:

(function ($) {
  $.fn.myFoo= function (o){
    var privateFunction = function (){ 
      alert('private');
    };

    var functions = {
      _min: function (){ 
        alert('_min');
      },
      max: function (){
        alert('max');
      }
    };


    functions[o](); // invoke the function
    // ...
    return this; // preserve the jQuery method "chainability"
  };
})(jQuery);

Edit: If you want to declare a "private function", (not invokable through your String argument), you can simply declare it as a variable in the $.fn.myFoo function.

It will be usable by all your "public functions" (all the members of the functions object) but you won't be able to execute it using your o argument.

CMS
+1 for using `return this;`
Joseph Silvashy
thank you. this helped me with my first question... for my second question ... _min turns out not to be a private function. however i could use something that could look if the first character = "_" using the substr(0,1). unless there is another trick :) to make the function _min as a private function
Val
If you want your `min` function to only be accessible within the `$.fn.myFoo` function but not invokable through your String argument, take it out from the `functions` object in my example, and declare it with the `var` statement, i.e.: `var min = function () {};
CMS
thank you... you have all the answers lol wikipedia.com
Val