0

I am using the following pattern to write a javascript library, but it couldn't receive parameters passed into the functions, am I missing something here?

(function($){

    var Foo = function(elements, options){
    ... ...
    }


    Foo.prototype = {

        constructor: Foo,

        bar: function(arg){        
            console.log(arg);     // print 'undefined' here
        },

    }

    $.fn.foo = function(option){
        return this.each(function(){
        ... ...
        })
    }

    $.fn.foo.Constructor = Bricker

    $.fn.foo.defaults = {
        ... ...
    }

})(jQuery)

When I call $('select').foo('bar', content), content will be logged as 'undefined', can anyone tell me the problems?

Jensen
  • 1,653
  • 4
  • 26
  • 42
  • 2
    Your `$.fn.foo()` method only takes one argument (`option`), so the second argument you're passing (`content`) is not actually accessible within its scope. Try `$.fn.foo = function(option, content) { /* ... */ };`. – Frédéric Hamidi Apr 25 '12 at 22:57
  • @FrédéricHamidi it still says 'undefined' – Jensen Apr 25 '12 at 23:06
  • Then I'm afraid you'll have to fill the dots in your question, because it will be hard to answer without seeing how `$.fn.foo()` ends up calling `Foo.bar()`. – Frédéric Hamidi Apr 25 '12 at 23:24
  • @FrédéricHamidi I've found out the problem. You are right, I didn't pass the second argument to the functions. Thanks you. – Jensen Apr 25 '12 at 23:33

1 Answers1

0

In this case Foo.prototype and $.fn.foo both are working differently try the below code for creating jquery function like,

;(function(){
    $.fn.foo = function(name,value){
       console.log(name,value);
    };
})(jQuery);

You can call it by any jquery-selector like

$('#id').foo('bar','value');// check your console to see the magic.

And, your second scenario(prototype) is somehow different, in which you are using prototype method(which differs from jQuery.fn), to work your code try the below,

var Foo = function() {};
Foo.prototype = {
    constructor: Foo,
    bar: function(arg){        
        console.log(arg); // print 'test' here
    }
};
var f=new Foo();
f.bar('test');

;(function($){
    $.fn.foo = function(name,value){
           console.log(name,value);
    };
})(jQuery);
$(document).foo('bar','value');

var Foo = function() {};
Foo.prototype = {
    constructor: Foo,
    bar: function(arg){        
        console.log(arg);     // print 'undefined' here
    }
};
var f=new Foo();
f.bar('test');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

And a jsfiddle and an explanatory answer for your doubts.

Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106