Search code examples
javascriptjqueryfunctionobjectextend

jquery fn.extend() returning values and call values in object


I need some help in understanding something, that propably is easy for serious jquery and javascript programmers.

Lets say I have a code like this:

jQuery.fn.extend({
   myNameSpace: {
     myPlugIn: function (o) { 
       var o = { variable : o.variable || false };

      var myfunction = function(v) {
      o.variable = v;
      };
      return {
         myfunction : myfunction
      };

    }
});

and now I am able to call that with:

x = new $.myNameSpace.myPlugIn({variable : 99}) ;

and then I call my function myfunction like this

x.myfunction(20);

I can understand that, now the question: how can I get the value of variable inside my plug in.

I tried something like alert(x.o[variable]); etc. but I just cant get it - It must be easy...

What I try to accomplish is a value I could call if something inside the plugin is finished, or calculated.


Solution

  • You can not get the variables inside with your current code, unless you change it to:

    var myfunction = function(v) {
        o.variable = v;
        return v;  //or o.variable
    };
    
    //...
    x.myfunction(20)  //20;
    

    Added

    It seems like you are trying to make a plugin for jQuery. To create a plugin, you do not use $.extend. $.extend is only used to preset default settings. [1] Normally this is how you set up a plugin:

    (function($) {
        var methods = {
            getVar: function(){ 
                return $.extend({
                    data: data,
                }, methods);
            },
            setVar: function(d){ 
                data = d;
                return methods;
            }
        },
        data = {};
    
        $.fn.myPlugin = function(options) {
            //do stuff
            data = $.extend( data , options );
    
            return methods;
        };
    })(jQuery);
    

    http://jsfiddle.net/DerekL/wv5QH/1/